Reusing http connections in Go

go

Solution

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:

- Read until Response is complete (i.e. `ioutil.ReadAll(resp.Body)`)

- Call `Body.Close()`

Problem

I'm currently struggling to find a way to reuse connections when making HTTP posts in Go. I've created a transport and client like so: ``` // Create a new transport and HTTP client tr := &http.Transport{} client := &http.Client{Transport: tr} ``` I'm then passing this client pointer into a goroutine which is making multiple posts to the same endpoint like so: ``` r, err := client.Post(url, "application/json", post) ``` Looking at netstat this appears to be resulting in a new connection for every post resulting in a large number of concurrent connections being open. What is the correct way to reuse connections in this case?

Original source

Related problems