Home >Backend Development >Golang >How to Effectively Disable Connection Pooling for Go's http.Client?
Disabling Connection Pooling for Go http.Client
In Go's HTTP client, connection pooling allows for efficient reuse of connections between requests to the same host. However, for testing purposes, disabling connection pooling may be necessary to establish a new TCP connection for each HTTP/1.x request.
Using DisableKeepAlives or MaxIdleConnsPerHost
Connections are typically added to a pool in Transport.tryPutIdleConn. To disable pooling, set either Transport.DisableKeepAlives to true or Transport.MaxIdleConnsPerHost to a negative value:
func disableKeepAlive(c *http.Client) { t := c.Transport.(*http.Transport) t.DisableKeepAlives = true } func disableMaxIdle(c *http.Client) { t := c.Transport.(*http.Transport) t.MaxIdleConnsPerHost = -1 }
Using Dialer.KeepAlive
Despite initial assumptions, setting the Dialer.KeepAlive option does not disable pooling.
Possible Race Condition
Setting Transport.IdleConnTimeout to a very short duration (e.g., 1 nanosecond) may result in "tls: use of closed connection" errors due to a potential race condition in the Go standard library.
Recommended Approach
To ensure that connection pooling is disabled, it is recommended to clone the default transport and modify its options:
func disablePooling(c *http.Client) { t := c.Transport.(*http.Transport).Clone() t.MaxIdleConnsPerHost = -1 t.DisableKeepAlives = true }
This approach allows for customization of various transport options while preserving the defaults.
The above is the detailed content of How to Effectively Disable Connection Pooling for Go's http.Client?. For more information, please follow other related articles on the PHP Chinese website!