github.com/discordapp/buildkite-agent@v2.6.6+incompatible/api/auth.go (about) 1 package api 2 3 import ( 4 "fmt" 5 "net/http" 6 ) 7 8 type canceler interface { 9 CancelRequest(*http.Request) 10 } 11 12 // Transport manages injection of the API token 13 type AuthenticatedTransport struct { 14 // The Token used for authentication. This can either the be 15 // organizations registration token, or the agents access token. 16 Token string 17 18 // Transport is the underlying HTTP transport to use when making 19 // requests. It will default to http.DefaultTransport if nil. 20 Transport http.RoundTripper 21 } 22 23 // RoundTrip invoked each time a request is made 24 func (t AuthenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) { 25 if t.Token == "" { 26 return nil, fmt.Errorf("Invalid token, empty string supplied") 27 } 28 29 req.Header.Set("Authorization", fmt.Sprintf("Token %s", t.Token)) 30 31 return t.transport().RoundTrip(req) 32 } 33 34 // Client builds a new http client. 35 func (t *AuthenticatedTransport) Client() *http.Client { 36 return &http.Client{Transport: t} 37 } 38 39 // CancelRequest cancels an in-flight request by closing its connection. 40 func (t *AuthenticatedTransport) CancelRequest(req *http.Request) { 41 cancelableTransport := t.Transport.(canceler) 42 cancelableTransport.CancelRequest(req) 43 } 44 45 func (t *AuthenticatedTransport) transport() http.RoundTripper { 46 // Use the custom transport if one was provided 47 if t.Transport != nil { 48 return t.Transport 49 } 50 51 return http.DefaultTransport 52 }