From d1f17ef429933ca68c3ee05b65e6c8e55c3fc6a7 Mon Sep 17 00:00:00 2001 From: Thomas Gosteli Date: Tue, 20 Mar 2018 16:28:12 +0100 Subject: [PATCH] implement WithHeader function, for custom headers to be set in each request --- httpclient.go | 14 ++++++++++++++ httpclient_test.go | 13 +++++++++++++ 2 files changed, 27 insertions(+) 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))