Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ func (c *Client) Do(req *http.Request) (*http.Response, error) {

// JSON
//
// DoJSON, GetJSON, PostJSON, PutJSON, and DeleteJSON all set the appropriate
// JSON headers and decode the response body into the target. Pass nil as
// target to skip decoding — useful for endpoints that return no body (e.g.
// 204 No Content).

func (c *Client) DoJSON(req *http.Request, target any) error {
req.Header.Set("Content-Type", "application/json")
Expand All @@ -84,7 +88,12 @@ func (c *Client) DoJSON(req *http.Request, target any) error {
return fmt.Errorf("got %d code and response: %s", resp.StatusCode, string(body))
}

if err := json.NewDecoder(resp.Body).Decode(&target); err != nil {
if target == nil {
Comment thread
dankinder marked this conversation as resolved.
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}

if err := json.NewDecoder(resp.Body).Decode(target); err != nil {
return fmt.Errorf("got %d code and failed to decode response body: %w", resp.StatusCode, err)
}
return nil
Expand Down
13 changes: 13 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,19 @@ func TestClientDoJSON(t *testing.T) {
assert.Equal(t, "joebob", user.Name)
}

func TestClientDoJSONNilTarget204(t *testing.T) {
handler, client, cleanup := setup(t)
defer cleanup()

handler.On("HandleWithHeaders", "DELETE", "/users/1", jsonHeaderMatcher, mock.Anything).Return(httpmock.Response{
Status: http.StatusNoContent,
})

req, err := http.NewRequest("DELETE", "/users/1", nil)
require.NoError(t, err)
require.NoError(t, client.DoJSON(req, nil))
}

type TestUser struct {
ID int `json:"id,omitempty"`
Name string `json:"name"`
Expand Down
Loading