Skip to content

fix(http): close response body in StrictHTTPClient.Do - #4621

Open
stevenvegt wants to merge 2 commits into
masterfrom
fix/4620-close-response-body
Open

stevenvegt wants to merge 2 commits into
masterfrom
fix/4620-close-response-body

Conversation

@stevenvegt

Copy link
Copy Markdown
Member

Problem

StrictHTTPClient.Do replaces the response body with an in-memory copy read through limitedReadAll, but never closes the original body. When a response exceeds the maximum size, the error is returned with the body still open, so the connection is held until the client timeout. With MaxConnsPerHost = 5 on SafeHttpTransport, a server returning oversized bodies can occupy every connection slot for that host. On the success path the original body was not closed either.

Fix

Close the original body (deferred, right after the nil check) on both the error and success paths. On overflow the body is closed without draining, so the connection is dropped rather than reused. The limit semantics are unchanged.

Testing

New TestStrictHTTPClient_ClosesResponseBody wraps SafeHttpTransport in a round tripper that counts Close() calls on the response body. It asserts the body is closed both when Do fails because the response exceeds the limit and when Do succeeds. The test failed on the Close assertions before the fix and passes after it. go test -race ./http/client/ and go vet ./http/client/ pass.

V6.2 is backported in a separate PR. V5.4 is not affected: its strict client does not read the response body.

Fixes #4620

Do replaced the response body with an in-memory copy but never closed
the original. When a response exceeded the maximum size, the error was
returned with the body still open, so the connection stayed held until
the client timeout. With MaxConnsPerHost = 5, a server returning
oversized bodies could occupy every connection slot for that host.

The original body is now closed on both the error and success paths.
On overflow it is closed without draining, so the connection is
dropped rather than reused.

Assisted-by: AI
@qltysh

qltysh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

0 new issues

Tool Category Rule Count

This branch has not been deployed

No deployments
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.

StrictHTTPClient.Do does not close the response body on overflow

2 participants