Home >Backend Development >Golang >How to Effectively Disable Connection Pooling for Go's http.Client?

How to Effectively Disable Connection Pooling for Go's http.Client?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 21:07:02933browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn