lego/providers/dns/dynu/internal/auth.go

65 lines
1.5 KiB
Go
Raw Normal View History

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
}
// 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 != "" {
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}
}
// 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
}