2020-03-10 11:31:33 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-07-29 10:59:24 +00:00
|
|
|
// NewTokenTransport Creates an HTTP transport for API authentication.
|
2020-03-10 11:31:33 +00:00
|
|
|
func NewTokenTransport(apiKey string) (*TokenTransport, error) {
|
|
|
|
if apiKey == "" {
|
|
|
|
return nil, errors.New("credentials missing: API key")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &TokenTransport{apiKey: apiKey}, nil
|
|
|
|
}
|
|
|
|
|
2020-05-08 17:35:25 +00:00
|
|
|
// RoundTrip executes a single HTTP transaction.
|
2020-03-10 11:31:33 +00:00
|
|
|
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 != "" {
|
2020-10-17 12:51:55 +00:00
|
|
|
enrichedReq.Header.Set(apiKeyHeader, t.apiKey)
|
2020-03-10 11:31:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return t.transport().RoundTrip(enrichedReq)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TokenTransport) transport() http.RoundTripper {
|
|
|
|
if t.Transport != nil {
|
|
|
|
return t.Transport
|
|
|
|
}
|
|
|
|
return http.DefaultTransport
|
|
|
|
}
|
|
|
|
|
2020-05-08 17:35:25 +00:00
|
|
|
// Client Creates a new HTTP client.
|
2020-03-10 11:31:33 +00:00
|
|
|
func (t *TokenTransport) Client() *http.Client {
|
|
|
|
return &http.Client{Transport: t}
|
|
|
|
}
|
|
|
|
|
2022-11-27 19:04:28 +00:00
|
|
|
// Wrap wraps an HTTP client Transport with the TokenTransport.
|
2020-03-10 11:31:33 +00:00
|
|
|
func (t *TokenTransport) Wrap(client *http.Client) *http.Client {
|
|
|
|
backup := client.Transport
|
|
|
|
t.Transport = backup
|
|
|
|
client.Transport = t
|
|
|
|
|
|
|
|
return client
|
|
|
|
}
|