prevent baseClient from trying to decode 204 responses (#16060)

noticed while working on #15916, we do a request that, when successful,
returns a 204 response (with no content)

currently the client will fail to parse the contents of the response and
return an error "response: unexpected end of JSON input, body" even if
the request was succesful.
This commit is contained in:
Roberto Dip 2024-01-11 17:55:35 -03:00 committed by GitHub
parent 0f3458b2a0
commit ca06f0aed6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 17 additions and 1 deletions

View file

@ -0,0 +1 @@
* improve the HTTP client used by `fleetctl` and `fleetd` to prevent errors for 204 responses.

View file

@ -0,0 +1 @@
* improve the HTTP client used by `fleetctl` and `fleetd` to prevent errors for 204 responses.

View file

@ -63,7 +63,7 @@ func (bc *baseClient) parseResponse(verb, path string, response *http.Response,
bc.setServerCapabilities(response)
if responseDest != nil {
if responseDest != nil && response.StatusCode != http.StatusNoContent {
b, err := io.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("reading response body: %w", err)

View file

@ -70,6 +70,20 @@ func TestParseResponseOK(t *testing.T) {
require.Equal(t, "ok", resDest.Test)
}
func TestParseResponseOKNoContent(t *testing.T) {
bc, err := newBaseClient("https://test.com", true, "", "", nil, fleet.CapabilityMap{})
require.NoError(t, err)
response := &http.Response{
StatusCode: http.StatusNoContent,
Body: io.NopCloser(bytes.NewBufferString("")),
}
var resDest struct{ Err error }
err = bc.parseResponse("", "", response, &resDest)
require.NoError(t, err)
require.Nil(t, resDest.Err)
}
func TestParseResponseGeneralErrors(t *testing.T) {
t.Run("general HTTP errors", func(t *testing.T) {
bc, err := newBaseClient("https://test.com", true, "", "", nil, fleet.CapabilityMap{})