diff --git a/httpclient.go b/httpclient.go index 8f66c3b..7f031d1 100644 --- a/httpclient.go +++ b/httpclient.go @@ -52,7 +52,7 @@ type Client struct { username string password string - // custom http header + // custom http header(s) header http.Header Marshaler MarshalerFunc @@ -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 @@ -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) @@ -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) diff --git a/httpclient_test.go b/httpclient_test.go index 813b638..1a37c2b 100644 --- a/httpclient_test.go +++ b/httpclient_test.go @@ -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))