Skip to content

Commit

Permalink
Close response body in defer to prevent mistakes
Browse files Browse the repository at this point in the history
  • Loading branch information
guseggert committed Mar 21, 2023
1 parent 4dea63f commit 93b5f90
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions routing/http/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,18 +211,24 @@ func (c *client) FindProviders(ctx context.Context, key cid.Cid) (provs iter.Res

m.mediaType = mediaType

var skipBodyClose bool
defer func() {
if !skipBodyClose {
resp.Body.Close()
}
}()

var it iter.ResultIter[types.ProviderResponse]
switch mediaType {
case mediaTypeJSON:
defer resp.Body.Close()
parsedResp := &jsontypes.ReadProvidersResponse{}
err = json.NewDecoder(resp.Body).Decode(parsedResp)
var sliceIt iter.Iter[types.ProviderResponse] = iter.FromSlice(parsedResp.Providers)
it = iter.ToResultIter(sliceIt)
case mediaTypeNDJSON:
skipBodyClose = true
it = ndjson.NewReadProvidersResponseIter(resp.Body)
default:
defer resp.Body.Close()
logger.Errorw("unknown media type", "MediaType", mediaType, "ContentType", respContentType)
return nil, errors.New("unknown content type")
}
Expand Down

0 comments on commit 93b5f90

Please sign in to comment.