Skip to content

Commit

Permalink
Merge pull request #2 from ghouscht/master
Browse files Browse the repository at this point in the history
implement WithHeader function, for custom headers to be set in each request
  • Loading branch information
opensourcepf authored Mar 21, 2018
2 parents 0f563a1 + f7d4773 commit 7c700ad
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
15 changes: 15 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,15 @@ func WithContentType(ct string) Opt {
}
}

// WithHeader is a client option for setting custom http header(s) for each request
// Content-Type and Accept headers will always be overwritten by the clients ContentType setting
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 +229,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
15 changes: 15 additions & 0 deletions httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,21 @@ 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["X-Requested-By"], []string{"test"})
assert.Contains(t, req.Header, "Content-Type")
assert.Contains(t, req.Header, "Accept")
})

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 7c700ad

Please sign in to comment.