-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
auth.go
64 lines (50 loc) · 1.51 KB
/
auth.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 internal
import (
"errors"
"net/http"
)
const apiKeyHeader = "Api-Key"
// TokenTransport HTTP transport for API authentication.
type TokenTransport struct {
apiKey string
// Transport is the underlying HTTP transport to use when making requests.
// It will default to http.DefaultTransport if nil.
Transport http.RoundTripper
}
// NewTokenTransport Creates a HTTP transport for API authentication.
func NewTokenTransport(apiKey string) (*TokenTransport, error) {
if apiKey == "" {
return nil, errors.New("credentials missing: API key")
}
return &TokenTransport{apiKey: apiKey}, nil
}
// RoundTrip executes a single HTTP transaction.
func (t *TokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
enrichedReq := &http.Request{}
*enrichedReq = *req
enrichedReq.Header = make(http.Header, len(req.Header))
for k, s := range req.Header {
enrichedReq.Header[k] = append([]string(nil), s...)
}
if t.apiKey != "" {
enrichedReq.Header.Set(apiKeyHeader, t.apiKey)
}
return t.transport().RoundTrip(enrichedReq)
}
func (t *TokenTransport) transport() http.RoundTripper {
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}
// Client Creates a new HTTP client.
func (t *TokenTransport) Client() *http.Client {
return &http.Client{Transport: t}
}
// Wrap wraps an HTTP client Transport with the TokenTransport.
func (t *TokenTransport) Wrap(client *http.Client) *http.Client {
backup := client.Transport
t.Transport = backup
client.Transport = t
return client
}