auth.go raw

   1  package internal
   2  
   3  import (
   4  	"errors"
   5  	"net/http"
   6  )
   7  
   8  const apiKeyHeader = "Api-Key"
   9  
  10  // TokenTransport HTTP transport for API authentication.
  11  type TokenTransport struct {
  12  	apiKey string
  13  
  14  	// Transport is the underlying HTTP transport to use when making requests.
  15  	// It will default to http.DefaultTransport if nil.
  16  	Transport http.RoundTripper
  17  }
  18  
  19  // NewTokenTransport Creates an HTTP transport for API authentication.
  20  func NewTokenTransport(apiKey string) (*TokenTransport, error) {
  21  	if apiKey == "" {
  22  		return nil, errors.New("credentials missing: API key")
  23  	}
  24  
  25  	return &TokenTransport{apiKey: apiKey}, nil
  26  }
  27  
  28  // RoundTrip executes a single HTTP transaction.
  29  func (t *TokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  30  	enrichedReq := &http.Request{}
  31  	*enrichedReq = *req
  32  
  33  	enrichedReq.Header = make(http.Header, len(req.Header))
  34  	for k, s := range req.Header {
  35  		enrichedReq.Header[k] = append([]string(nil), s...)
  36  	}
  37  
  38  	if t.apiKey != "" {
  39  		enrichedReq.Header.Set(apiKeyHeader, t.apiKey)
  40  	}
  41  
  42  	return t.transport().RoundTrip(enrichedReq)
  43  }
  44  
  45  func (t *TokenTransport) transport() http.RoundTripper {
  46  	if t.Transport != nil {
  47  		return t.Transport
  48  	}
  49  
  50  	return http.DefaultTransport
  51  }
  52  
  53  // Client Creates a new HTTP client.
  54  func (t *TokenTransport) Client() *http.Client {
  55  	return &http.Client{Transport: t}
  56  }
  57  
  58  // Wrap wraps an HTTP client Transport with the TokenTransport.
  59  func (t *TokenTransport) Wrap(client *http.Client) *http.Client {
  60  	backup := client.Transport
  61  	t.Transport = backup
  62  	client.Transport = t
  63  
  64  	return client
  65  }
  66