Skip to content

Commit

Permalink
no longer override Authorization header when using WithHeader to set …
Browse files Browse the repository at this point in the history
…custom headers
  • Loading branch information
ghouscht committed Mar 22, 2018
1 parent 765db41 commit ed57d9f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
13 changes: 7 additions & 6 deletions httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ type Client struct {
username string
password string

// custom http header
// custom http header(s)
header http.Header

Marshaler MarshalerFunc
Expand Down Expand Up @@ -191,7 +191,8 @@ 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
// Content-Type and Accept headers will be appended by the clients ContentType setting
// Authorization header is overwritten if WithUsername/WithPassowrd was used to setup the client
func WithHeader(header http.Header) Opt {
return func(c *Client) error {
c.header = header
Expand Down Expand Up @@ -225,13 +226,13 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ
return nil, err
}

if len(c.username) > 0 && len(c.password) > 0 {
req.SetBasicAuth(c.username, c.password)
}

if c.header != nil {
req.Header = c.header
}

if len(c.username) > 0 && len(c.password) > 0 {
req.SetBasicAuth(c.username, c.password)
}
req.Header.Add("Content-Type", contentType)
req.Header.Add("Accept", contentType)

Expand Down
19 changes: 19 additions & 0 deletions httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,25 @@ func TestClient(t *testing.T) {
assert.Contains(t, req.Header, "Accept")
})

t.Run("new client with headers and basic auth", func(t *testing.T) {
username := "user1"
password := "123456"
fakeAuthHeader := http.Header{
"Authorization": []string{"fake"},
}

c, err := New(baseurl, WithHeader(fakeAuthHeader), WithUsername(username), WithPassword(password))
assert.Nil(t, err)
assert.NotNil(t, c)

req, err := c.NewRequest(http.MethodGet, "/test", nil)
assert.Nil(t, err)
user, passwd, ok := req.BasicAuth()
assert.True(t, ok)
assert.Equal(t, user, username)
assert.Equal(t, passwd, passwd)
})

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 ed57d9f

Please sign in to comment.