Middle+
What are the consequences of creating a new HTTP client for each request?
sobes.tech AI
Answer from AI
Creating a new HTTP client for each request in Go leads to several issues:
-
Loss of connection reuse benefits (Keep-Alive): The HTTP client manages a connection pool, and creating a new client each time establishes new TCP connections, increasing latency and network load.
-
Increased resource consumption: Frequent creation and destruction of clients result in unnecessary memory and CPU usage.
-
Risk of resource leaks: If the transport or connections are not properly closed, it can lead to file descriptor leaks.
The correct approach is to create a single instance of http.Client and reuse it for multiple requests:
var client = &http.Client{}
func makeRequest(url string) (*http.Response, error) {
return client.Get(url)
}
This allows efficient use of connections and reduces system load.