I\'m currently struggling to find a way to reuse connections when making HTTP posts in Golang.
I\'ve created a transport and client like so:
// Crea
Edit: This is more of a note for people that construct a Transport and Client for every request.
Edit2: Changed link to godoc.
Transport
is the struct that holds connections for re-use; see https://godoc.org/net/http#Transport ("By default, Transport caches connections for future re-use.")
So if you create a new Transport for each request, it will create new connections each time. In this case the solution is to share the one Transport instance between clients.
Another approach to init()
is to use a singleton method to get the http client. By using sync.Once you can be sure that only one instance will be used on all your requests.
var (
once sync.Once
netClient *http.Client
)
func newNetClient() *http.Client {
once.Do(func() {
var netTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: 2 * time.Second,
}).Dial,
TLSHandshakeTimeout: 2 * time.Second,
}
netClient = &http.Client{
Timeout: time.Second * 2,
Transport: netTransport,
}
})
return netClient
}
func yourFunc(){
URL := "local.dev"
req, err := http.NewRequest("POST", URL, nil)
response, err := newNetClient().Do(req)
// ...
}
Ensure that you read until the response is complete AND call Close()
.
e.g.
res, _ := client.Do(req)
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
Again... To ensure http.Client
connection reuse be sure to:
ioutil.ReadAll(resp.Body)
)Body.Close()