Home > Mobile >  go multiple http clients with different tls configs
go multiple http clients with different tls configs

Time:08-17

Trying to implement multiple http clients for calling multiple services, each with their own tls configurations (some need mTLS while some do not). However, I am seeing that the each new request is using the tls config from prior request, and not its own tls config? For example, I have 2 clients as below. When client-1 makes the first request, it verifies the server cert as expected. But when client-2 makes the next request, it is still trying to verify the server cert even though InsecureSkipVerify: true is configured for it.

client-1 has config:

tr := http.DefaultTransport.(*http.Transport)
tr.TLSClientConfig = &tls.Config{RootCAs: certPool, InsecureSkipVerify: false}
client1 := http.Client{Transport: tr, Timeout: timeout}

client-2 has config:

tr := http.DefaultTransport.(*http.Transport)
tr.TLSClientConfig = &tls.Config{RootCAs: certPool, InsecureSkipVerify: true}
client2 := http.Client{Transport: tr, Timeout: timeout}

response for the client2 request is x509: certificate signed by unknown authority. This shouldn't ideally happen because InsecureSkipVerify: true means the server certs are not verified.

CodePudding user response:

http.DefaultTransport is a variable defined in the http package (here) as:

var DefaultTransport RoundTripper = &Transport{
    Proxy: ProxyFromEnvironment,
    DialContext: defaultTransportDialContext(&net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
    }),
    ForceAttemptHTTP2:     true,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

You can use DefaultTransport to create multiple instances of http.Client but need to remember that they will all be using the same Transport (DefaultTransport). Changes to DefaultTransport will have an impact on all instances of http.Client that use DefaultTransport.

To resolve this either define your own Transport (perhaps by copying the above, this is covered in the docs) or make a copy (tr := http.DefaultTransport.(*http.Transport).Clone()) of the default transport before changing TLSClientConfig.

  • Related