Home >Backend Development >Golang >How Can I Efficiently Reuse HTTP Connections in Go?

How Can I Efficiently Reuse HTTP Connections in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 04:29:08500browse

How Can I Efficiently Reuse HTTP Connections in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn