3
votes

in GO net/http Response Body annotation says:

It is the caller's responsibility to close Body. The default HTTP client's Transport does not attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections ("keep-alive") unless the Body is read to completion and is closed.

It's mean: if I use http.Get and don't call resp.Body.Close() then it will not resue HTTP/1.0 or HTTP/1.1 TCP connections ("keep-alive") yeah?

so I write some code:

package main

import ( "time" "fmt" "io/ioutil" "net/http" )

func main() { resp, err := http.Get("http://127.0.0.1:8588")

if err != nil {
    panic(err)
}
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
    panic(err)
}

resp2, err := http.Get("http://127.0.0.1:8588")

if err != nil {
    panic(err)
}
_, err = ioutil.ReadAll(resp2.Body)
if err != nil {
    panic(err)
}

fmt.Println("before time sleep")
time.Sleep(time.Second * 35)

}

and I only see ONE tcp connection build in wireshark, why? I don't close res.Body so the http client should't be reuse the tcp connection.
2
Perhaps the comment is wrong. Once the response body is read to EOF, there's nothing preventing the client from reusing the connection.Cerise Limón
@CeriseLimón yes, it's a error on comment. github.com/golang/go/issues/22954 but the response body not read EOF. just read content-Length in http header then read Content-Length bytes from body.loin.liao
"Read to EOF" shorthand for "read to the end of the response body". Reading content-length bytes is reading to the end of the response body.Cerise Limón

2 Answers

0
votes

You have read it till the end in first occurence of line:

_, err = ioutil.ReadAll(resp.Body)

So the connection is ready to be resused. Try not to read and run again.