Closed guest6379 closed 1 year ago
There's a couple of things needed to avoid the leak:
http.DefaultClient.CloseIdleConnections
to close idle connections.Updated test code that doesn't leak:
func TestXxx(t *testing.T) {
defer goleak.VerifyNone(t)
resp, err := http.Get("https://www.microsoft.com")
if err != nil {
t.Fail()
}
defer resp.Body.Close()
defer http.DefaultClient.CloseIdleConnections()
fmt.Println(resp.StatusCode)
ioutil.ReadAll(resp.Body)
}
There's a couple of things needed to avoid the leak:
* Read the response body. This shouldn't be needed as the body is closed, but I saw failures unless the body was read, and I think it might be related to: [x/net/http2: RoundTrip and/or CloseIdleConnections may leave connections in use after returning golang/go#50027](https://github.com/golang/go/issues/50027) * Call [`http.DefaultClient.CloseIdleConnections`](https://pkg.go.dev/net/http#Client.CloseIdleConnections) to close idle connections.
Updated test code that doesn't leak:
func TestXxx(t *testing.T) { defer goleak.VerifyNone(t) resp, err := http.Get("https://www.microsoft.com") if err != nil { t.Fail() } defer resp.Body.Close() defer http.DefaultClient.CloseIdleConnections() fmt.Println(resp.StatusCode) ioutil.ReadAll(resp.Body) }
Thank you so much for the explanatory code snippet, have a nice day
os platform: ubuntu 20.04 go version: 1.19.7
Can someone advise me how to pass the test? Is the problem caused by the running time
FAIL demo/test 1.169s
?OUTPUT: