Home > Backend Development > Golang > How can I Disable Connection Pooling in Go's http.Client for Fresh TCP Connections?

How can I Disable Connection Pooling in Go's http.Client for Fresh TCP Connections?

Patricia Arquette
Release: 2024-11-07 17:17:03
Original
925 people have browsed it

How can I Disable Connection Pooling in Go's http.Client for Fresh TCP Connections?

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}
Copy after login

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}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template