Skip to content

[http] Close the response body when reading it fails - #1476

Merged
manugarg merged 1 commit into
mainfrom
http-close-body-on-read-error
Sep 9, 2026
Merged

manugarg merged 1 commit into
mainfrom
http-close-body-on-read-error

Conversation

@manugarg

@manugarg manugarg commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

doHTTPRequest closes the response body on the negative-test path and on the
normal path, but the io.ReadAll error path returned without closing it:

respBody, err := io.ReadAll(resp.Body)
if err != nil {
        err = p.redactedErr(err)
        l.WithAttributes(p.dynamicHeaderAttrs(req)...).Warning(err.Error())
        return err          // <- body never closed
}

An unclosed body holds its connection out of the idle pool, so a server that
keeps truncating or resetting responses leaks one connection per probe instead
of reusing them.

Why not defer resp.Body.Close()

That would be the more idiomatic shape, but the success path closes the body
before validators.RunValidators runs, and validators are user-configured and
can be slow. Deferring would hold the connection open across them and change
when it returns to the idle pool. The explicit close keeps the existing timing.

Testing

TestResponseBodyClosedOnReadError drives doHTTPRequest through a transport
whose response body fails every read, and asserts the body was closed. Verified
that it fails without the fix ("response body must be closed on the read-error
path") and passes with it.

go build ./..., go vet, go test -race ./probes/http/... and gofmt are all
clean.

Noticed while reviewing #1410; the bug predates it.

doHTTPRequest closes the body on the negative-test path and on the normal
path, but the io.ReadAll error path returned without closing. An unclosed
body holds its connection out of the idle pool, so a server that keeps
truncating or resetting responses leaks one connection per probe rather
than reusing them.

Close it there too. Keeping the explicit close rather than switching the
function to a deferred one preserves the existing behaviour of releasing
the connection before validators run, which can be slow.
@manugarg
manugarg merged commit dcb39f9 into main Sep 9, 2026
13 checks passed
@manugarg
manugarg deleted the http-close-body-on-read-error branch September 9, 2026 01:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant