Home > Article > Backend Development > How can I disable connection pooling in Go's HTTP clients for testing purposes?
In testing scenarios, it may be necessary to disable connection pooling in Go's HTTP clients to create new TCP connections for each HTTP/1.x request. This guide explores various approaches to achieve this.
The default http.Transport used by http.Client enables connection pooling, which can be inconvenient. To disable pooling, you can set Transport.MaxIdleConnsPerHost to a negative value or set Transport.DisableKeepAlives to true.
Keep-alives are commonly used to maintain persistent connections, but setting Transport.DisableKeepAlives to true forces the client to close connections after each request. This approach adds a "Connection: close" request header and can be set as follows:
t := http.DefaultTransport.(*http.Transport).Clone() t.DisableKeepAlives = true c := &http.Client{Transport: t}
MaxIdleConnsPerHost, when set to -1, limits the number of idle connections per host to 0. This effectively disables pooling:
t := http.DefaultTransport.(*http.Transport).Clone() t.MaxIdleConnsPerHost = -1 c := &http.Client{Transport: t}
Dialer.KeepAlive may seem like an option for disabling pooling, but it only sets the keep-alive period for active connections. Pooling is not affected by this setting.
If desired, you can combine the options above with custom settings for DialContext, TLSHandshakeTimeout, ResponseHeaderTimeout, and ExpectContinueTimeout in the Transport object used by the http.Client.
It's important to note that pooling limitations are not limited to the number of active connections per host. However, options such as MaxIdleConnsPerHost and DisableKeepAlives provide effective methods for disabling pooling for testing purposes.
The above is the detailed content of How can I disable connection pooling in Go's HTTP clients for testing purposes?. For more information, please follow other related articles on the PHP Chinese website!