在 GO net/http Response Body 注释中说:
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.
这意味着:如果我使用 http.Get 并且不调用 resp.Body.Close() 那么它不会恢复 HTTP/1.0 或 HTTP/1.1 TCP 连接(“保持事件”)是吗?
所以我写了一些代码:
package main我在 wireshark 中只看到一个 tcp 连接,为什么? 我没有关闭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)
}
res.Body
所以 http
客户端不应该重用 tcp 连接。
最佳答案
这个问题已经解决了 https://github.com/golang/go/issues/22954 .
关于sockets - Go http.Get 什么时候重用 tcp 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47587153/