Skip to content

Commit 76fbd61

Browse files
committed
net/http: do not cancel request context on response body read
When sending a Request with a non-context deadline, we create a context with a timeout. This context is canceled when closing the response body, and also if a read from the response body returns an error (including io.EOF). Cancelling the context in Response.Body.Read interferes with the HTTP/2 client cleaning up after a request is completed, and is unnecessary: The user should always close the body, the impact from not canceling the context is minor (the context timer leaks until it fires). Fixes #49366. Change-Id: Ieaed866116916261d9079f71d8fea7a7b303b8fb Reviewed-on: https://go-review.googlesource.com/c/go/+/361919 Trust: Damien Neil <[email protected]> Run-TryBot: Damien Neil <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 9519651 commit 76fbd61

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/net/http/client.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -965,7 +965,6 @@ func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
965965
if err == nil {
966966
return n, nil
967967
}
968-
b.stop()
969968
if err == io.EOF {
970969
return n, err
971970
}

src/net/http/client_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1368,6 +1368,33 @@ func TestClientTimeoutCancel(t *testing.T) {
13681368
}
13691369
}
13701370

1371+
func TestClientTimeoutDoesNotExpire_h1(t *testing.T) { testClientTimeoutDoesNotExpire(t, h1Mode) }
1372+
func TestClientTimeoutDoesNotExpire_h2(t *testing.T) { testClientTimeoutDoesNotExpire(t, h2Mode) }
1373+
1374+
// Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1375+
func testClientTimeoutDoesNotExpire(t *testing.T, h2 bool) {
1376+
setParallel(t)
1377+
defer afterTest(t)
1378+
1379+
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1380+
w.Write([]byte("body"))
1381+
}))
1382+
defer cst.close()
1383+
1384+
cst.c.Timeout = 1 * time.Hour
1385+
req, _ := NewRequest("GET", cst.ts.URL, nil)
1386+
res, err := cst.c.Do(req)
1387+
if err != nil {
1388+
t.Fatal(err)
1389+
}
1390+
if _, err = io.Copy(io.Discard, res.Body); err != nil {
1391+
t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1392+
}
1393+
if err = res.Body.Close(); err != nil {
1394+
t.Fatalf("res.Body.Close() = %v, want nil", err)
1395+
}
1396+
}
1397+
13711398
func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
13721399
func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
13731400
func testClientRedirectEatsBody(t *testing.T, h2 bool) {

0 commit comments

Comments
 (0)