Skip to content

Commit

Permalink
Send the headers and body to option functions. This lets us avoid dea…
Browse files Browse the repository at this point in the history
…ling with creating a reader every time we call an option function.
  • Loading branch information
ggreer committed Feb 28, 2024
1 parent 3ba6179 commit 550df2a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
21 changes: 15 additions & 6 deletions pkg/uhttp/wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type (
HttpClient *http.Client
}

DoOption func(*http.Response) error
DoOption func(*http.Header, []byte) error
RequestOption func() (io.ReadWriter, map[string]string, error)
)

Expand All @@ -31,9 +31,8 @@ func NewBaseHttpClient(httpClient *http.Client) *BaseHttpClient {
}

func WithJSONResponse(response interface{}) DoOption {
return func(resp *http.Response) error {
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(response)
return func(resp *http.Header, body []byte) error {
return json.Unmarshal(body, response)
}
}

Expand All @@ -43,10 +42,20 @@ func (c *BaseHttpClient) Do(req *http.Request, options ...DoOption) (*http.Respo
return nil, err
}

defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = resp.Body.Close()
if err != nil {
return nil, err
}

// Replace resp.Body with a no-op closer so nobody has to worry about closing the reader.
resp.Body = io.NopCloser(bytes.NewBuffer(body))

for _, option := range options {
err = option(resp)
err = option(&resp.Header, body)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/uhttp/wrapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func TestWrapper_WithJSONResponse(t *testing.T) {

responseBody := example{}
option := WithJSONResponse(&responseBody)
err = option(&resp)
err = option(&resp.Header, exampleResponseBuffer.Bytes())

require.Nil(t, err)
require.Equal(t, exampleResponse, responseBody)
Expand Down

0 comments on commit 550df2a

Please sign in to comment.