This repository has been archived by the owner on Aug 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
64 lines (52 loc) · 1.41 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package goshikimori
import (
"context"
"errors"
"net/http"
"golang.org/x/oauth2"
)
// Transport for adding headers
type Transport struct {
// As User-Agent for Shikimori
ApplicationName string
Target http.RoundTripper
}
// AddTransport to context.
// If ctx.Value(oauth2.HTTPClient) == nil, then using
// DefaultTransport + Shikimori Transport
func AddTransport(ctx context.Context, appName string) context.Context {
ctxClient := ctx.Value(oauth2.HTTPClient)
var client *http.Client
if ctxClient == nil {
client = &http.Client{}
} else {
client = ctxClient.(*http.Client)
}
client.Transport = Transport{
ApplicationName: appName,
Target: client.Transport,
}
return context.WithValue(ctx, oauth2.HTTPClient, client)
}
// RoundTrip implements RoundTripper. Set User-Agent and call Transport.Target
func (tr Transport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", tr.ApplicationName)
req.Header.Set("Content-Type", "application/json")
resp, err := tr.target().RoundTrip(req)
if err != nil {
return resp, err
}
if !isTokenCorrect(resp) {
return resp, errors.New("The access token is invalid")
}
return resp, err
}
func isTokenCorrect(resp *http.Response) bool {
return resp.StatusCode != http.StatusUnauthorized
}
func (tr Transport) target() http.RoundTripper {
if tr.Target != nil {
return tr.Target
}
return http.DefaultTransport
}