Skip to content

Commit

Permalink
implement WithHeader function, for custom headers to be set in each r…
Browse files Browse the repository at this point in the history
…equest
  • Loading branch information
ghouscht committed Mar 20, 2018
1 parent 0f563a1 commit d1f17ef
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ type Client struct {
username string
password string

// custom http header
header http.Header

Marshaler MarshalerFunc
Unmarshaler UnmarshalerFunc

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down
13 changes: 13 additions & 0 deletions httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down

0 comments on commit d1f17ef

Please sign in to comment.