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

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

DDD
DDDOriginal
2024-11-08 16:01:02361browse

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:

  • Disabling connection pooling may reduce performance as new connections must be established for each request.
  • The default transport for http.Client uses TLS to encrypt connections. Disabling connection pooling may impact TLS session resumption and performance.

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!

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