-
Notifications
You must be signed in to change notification settings - Fork 301
/
auth.go
47 lines (37 loc) · 1.22 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
package api
import (
"fmt"
"net/http"
)
type canceler interface {
CancelRequest(*http.Request)
}
// Transport manages injection of the API token
type AuthenticatedTransport struct {
// The Token used for authentication. This can either the be
// organizations registration token, or the agents access token.
Token string
// Transport is the underlying HTTP transport to use when making
// requests. It will default to http.DefaultTransport if nil.
Transport http.RoundTripper
}
// RoundTrip invoked each time a request is made
func (t AuthenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.Token == "" {
return nil, fmt.Errorf("Invalid token, empty string supplied")
}
req.Header.Set("Authorization", fmt.Sprintf("Token %s", t.Token))
return t.transport().RoundTrip(req)
}
// CancelRequest cancels an in-flight request by closing its connection.
func (t *AuthenticatedTransport) CancelRequest(req *http.Request) {
cancelableTransport := t.Transport.(canceler)
cancelableTransport.CancelRequest(req)
}
func (t *AuthenticatedTransport) transport() http.RoundTripper {
// Use the custom transport if one was provided
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}