Skip to content

Commit

Permalink
Merge pull request #4 from ghouscht/master
Browse files Browse the repository at this point in the history
no longer override Authorization header when using WithHeader
  • Loading branch information
opensourcepf authored Mar 22, 2018
2 parents 7c700ad + ed57d9f commit 1ece438
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
15 changes: 8 additions & 7 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 Expand Up @@ -298,7 +299,7 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*htt
}()

if c.ResponseCallback == nil {
panic("CheckResponse is nil")
panic("ResponseCallback is nil")
}

resp, err = c.ResponseCallback(resp)
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 1ece438

Please sign in to comment.