Turning off Connection Pooling for Go http.Client
To achieve a fresh TCP connection for each HTTP/1.x request when testing, disabling the connection pooling mechanism in Go's HTTP client is essential. This can be accomplished by modifying the HTTP transport associated with the client.
One approach is to set DisableKeepAlives to true within the transport:
t := http.DefaultTransport.(*http.Transport).Clone() t.DisableKeepAlives = true c := &http.Client{Transport: t}
This option explicitly disables keep-alive connections, forcing the client to establish a new TCP connection for each request. However, it may add a Connection: close header to requests.
Alternatively, setting MaxIdleConnsPerHost to a negative value effectively disables pooling:
t := http.DefaultTransport.(*http.Transport).Clone() t.MaxIdleConnsPerHost = -1 c := &http.Client{Transport: t}
With this option, the transport will never add connections to the pool, ensuring that a new connection is established for every request.
Creating a new transport to store these settings is recommended to preserve the default transport configuration.
Setting Dialer.KeepAlive to -1 does not disable pooling as it primarily controls keep-alive behavior for active connections. Contrary to common assumptions, this option does not impact the number of TCP connections established.
Finally, setting IdleConnTimeout to a very short duration, such as 1 * time.Nanosecond, can also help ensure that idle connections are closed promptly. However, this approach should be used cautiously to avoid potential race conditions.
The above is the detailed content of How can I Disable Connection Pooling in Go's http.Client for Fresh TCP Connections?. For more information, please follow other related articles on the PHP Chinese website!