HTTP Connection Reuse in Go
When making multiple HTTP requests, it's essential to reuse connections to prevent unnecessary resource consumption and improve performance. In Go, this can be achieved by following a simple set of guidelines.
Firstly, create a global transport and HTTP client. This ensures that all requests are handled by the same underlying connection pool:
// Create a new transport and HTTP client tr := &http.Transport{} client := &http.Client{Transport: tr}
Next, always pass the same HTTP client to your goroutines that make HTTP requests:
r, err := client.Post(url, "application/json", post)
However, connection reuse is not enabled by default. To ensure it is properly utilized, it's crucial to read the entire HTTP response and explicitly close the body afterwards:
res, _ := client.Do(req) io.Copy(ioutil.Discard, res.Body) res.Body.Close()
By ensuring that the response is read completely and the body is closed, the connection can be safely returned to the pool for reuse in subsequent requests.
The above is the detailed content of How Can I Efficiently Reuse HTTP Connections in Go?. For more information, please follow other related articles on the PHP Chinese website!