diff --git a/httpclient.go b/httpclient.go index 8065a6b..27e86bd 100644 --- a/httpclient.go +++ b/httpclient.go @@ -133,6 +133,10 @@ func (hc *HTTPClient) setAuthentication(hr *http.Request) { hr.Header.Set("X-API-Key", hc.Config.apiKey) return } + if hc.bearerToken != "" { + hr.Header.Set("Authorization", "Bearer"+hc.bearerToken) + return + } if hc.authUser != "" && hc.authPass != "" { hr.SetBasicAuth(url.QueryEscape(hc.authUser), url.QueryEscape(hc.authPass)) } diff --git a/meteologix.go b/meteologix.go index 03daa27..e8698f7 100644 --- a/meteologix.go +++ b/meteologix.go @@ -46,6 +46,8 @@ type Config struct { authPass string // authUser holds the (optional) username for the API user authentication authUser string + // bearerToken holds the (optional) bearer token for the API authentication + bearerToken string // userAgent represents an alternative User-Agent HTTP header string userAgent string } @@ -97,6 +99,17 @@ func WithAPIKey(k string) Option { } } +// WithBearerToken uses a bearer token for the client authentication of the +// HTTP client +func WithBearerToken(t string) Option { + if t == "" { + return nil + } + return func(co *Config) { + co.bearerToken = t + } +} + // WithPassword sets the HTTP Basic auth authPass for the HTTP client func WithPassword(p string) Option { if p == "" { diff --git a/meteologix_test.go b/meteologix_test.go index bcfbb5d..33d1b6c 100644 --- a/meteologix_test.go +++ b/meteologix_test.go @@ -66,6 +66,28 @@ func TestNew_WithAPIKey(t *testing.T) { } } +func TestNew_WithBearerToken(t *testing.T) { + e := "BEARER-TOKEN" + c := New(WithBearerToken(e)) + if c == nil { + t.Errorf("NewWithBearerToken failed, expected Client, got nil") + return + } + if c.config.bearerToken != e { + t.Errorf("NewWithBearerToken failed, expected token value: %s, got: %s", e, + c.config.bearerToken) + } + c = New(WithBearerToken("")) + if c == nil { + t.Errorf("NewWithBearerToken failed, expected Client, got nil") + return + } + if c.config.bearerToken != "" { + t.Errorf("NewWithBearerToken failed, expected empty token, got: %s", + c.config.bearerToken) + } +} + func TestNew_WithUsername(t *testing.T) { e := "username" c := New(WithUsername(e))