How can I disable connection pooling for Go's http.Client?

Mary-Kate Olsen
Release: 2024-11-06 22:25:02
Original
474 people have browsed it

How can I disable connection pooling for Go's http.Client?

Turning Off Connection Pooling for Go http.Client

To disable connection pooling for Go's http.Client, you can modify its transport settings. There are two main approaches:

Approach 1: DisableKeepAlive

Setting Transport.DisableKeepAlives to true will prevent the transport from reusing existing connections. However, this may result in the addition of a Connection: close header to requests, which may not be desirable in all testing scenarios.

Approach 2: Set MaxIdleConnsPerHost

Setting Transport.MaxIdleConnsPerHost to a negative value, such as -1, will also effectively disable connection pooling. Unlike DisableKeepAlives, this approach will not affect request headers.

Sample Code

Here's an example of disabling connection pooling using DisableKeepAlive:

t := http.DefaultTransport.(*http.Transport).Clone()
t.DisableKeepAlives = true
c := &http.Client{Transport: t}
Copy after login

And here's an example using MaxIdleConnsPerHost:

t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConnsPerHost = -1
c := &http.Client{Transport: t}
Copy after login

It's important to note that setting Dialer.KeepAlive to -1 does not disable connection pooling. This setting only affects the keep-alive behavior of active connections, not the creation of new connections.

The above is the detailed content of How can I disable connection pooling for Go's http.Client?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!