Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does Go http.Get reuse the tcp connection?

Tags:

http

tcp

go

sockets

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.
like image 372
loin.liao Avatar asked Oct 28 '22 22:10

loin.liao


1 Answers

this problem has been solved in https://github.com/golang/go/issues/22954.

like image 58
loin.liao Avatar answered Jan 02 '23 21:01

loin.liao