Home > Article > Backend Development > How to Disable Connection Pooling for Go's http.Client?
Disabling Connection Pooling for Go http.Client
In Go, the net/http.Client manages connections to HTTP servers. By default, it uses connection pooling to improve performance by reusing existing connections. However, for testing purposes or certain use cases, it may be necessary to disable connection pooling.
To disable connection pooling for an http.Client, two methods can be used: setting Transport.DisableKeepAlives or setting Transport.MaxIdleConnsPerHost to -1.
Using Transport.DisableKeepAlives
The Transport.DisableKeepAlives field controls whether the transport disables keep-alive for requests. Setting it to true prevents connections from being kept open between requests. This method is recommended if disabling keep-alives is desired.
To disable keep-alives, use the following code:
import ( "net/http" "time" ) func main() { t := http.DefaultTransport.(*http.Transport).Clone() t.DisableKeepAlives = true c := &http.Client{Transport: t} // ... }
Using Transport.MaxIdleConnsPerHost
The Transport.MaxIdleConnsPerHost field controls the maximum number of idle connections per host. Setting it to -1 disables the connection pool by preventing any connections from being kept idle.
To disable connection pooling using this method, use the following code:
import ( "net/http" "time" ) func main() { t := http.DefaultTransport.(*http.Transport).Clone() t.MaxIdleConnsPerHost = -1 c := &http.Client{Transport: t} // ... }
Note:
Setting Dialer.KeepAlive to -1 does not disable connection pooling. Instead, it disables keep-alives for active connections, but connections are still managed in the connection pool.
Additional Considerations:
The above is the detailed content of How to Disable Connection Pooling for Go's http.Client?. For more information, please follow other related articles on the PHP Chinese website!