diff --git a/httpclient.go b/httpclient.go index 4682f2e..f34c2be 100644 --- a/httpclient.go +++ b/httpclient.go @@ -52,6 +52,9 @@ type Client struct { username string password string + // custom http header + header http.Header + Marshaler MarshalerFunc Unmarshaler UnmarshalerFunc @@ -187,6 +190,14 @@ func WithContentType(ct string) Opt { } } +// WithHeader is a client option for setting custom http header(s) for each request +func WithHeader(header http.Header) Opt { + return func(c *Client) error { + c.header = header + return nil + } +} + // NewRequest creates an API request. A relative URL can be provided in urlStr, which will be resolved to the // BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the // value pointed to by body will be encoded and included in as the request body. @@ -217,6 +228,9 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ req.SetBasicAuth(c.username, c.password) } + if c.header != nil { + req.Header = c.header + } req.Header.Add("Content-Type", contentType) req.Header.Add("Accept", contentType) diff --git a/httpclient_test.go b/httpclient_test.go index a6673a7..8ec7629 100644 --- a/httpclient_test.go +++ b/httpclient_test.go @@ -108,6 +108,19 @@ func TestClient(t *testing.T) { assert.Equal(t, password, c.password) }) + t.Run("new client with headers", func(t *testing.T) { + customHeader := http.Header{ + "X-Requested-By": []string{"test"}, + } + c, err := New(baseurl, WithHeader(customHeader)) + assert.Nil(t, err) + assert.NotNil(t, c) + + req, err := c.NewRequest(http.MethodGet, "/test", nil) + assert.Nil(t, err) + assert.Equal(t, req.Header, customHeader) + }) + t.Run("new client valid baseurl valid HTTP client", func(t *testing.T) { httpC := &http.Client{} c, err := New(baseurl, WithHTTPClient(httpC))