github.com/bshelton229/agent@v3.5.4+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  // CancelRequest cancels an in-flight request by closing its connection.
    35  func (t *AuthenticatedTransport) CancelRequest(req *http.Request) {
    36  	cancelableTransport := t.Transport.(canceler)
    37  	cancelableTransport.CancelRequest(req)
    38  }
    39  
    40  func (t *AuthenticatedTransport) transport() http.RoundTripper {
    41  	// Use the custom transport if one was provided
    42  	if t.Transport != nil {
    43  		return t.Transport
    44  	}
    45  
    46  	return http.DefaultTransport
    47  }