Nagri
Nagri

Reputation: 3136

How can I use tlsConfig with RoundTripper?

I have this code that implements an http client with a custom RoundTripper to add few header by default whenever Client is used to make http calls.

var Client *http.Client

type customTransport struct {
    underlyingTransport http.RoundTripper
}

func (t *customTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    req.Header.Add("Authorization", "Bearer")
    req.Header.Add("Version", "2017-11-23") 
    return t.underlyingTransport.RoundTrip(req)
}

func CreateClient() error {
    // Setup HTTPS client
    tlsConfig := &tls.Config{
        InsecureSkipVerify: true,
    }
    tlsConfig.BuildNameToCertificate()

    // transport := &http.Transport{TLSClientConfig: tlsConfig}
    // Client = &http.Client{Transport: transport}
    Client = &http.Client{Transport: &customTransport{underlyingTransport: http.DefaultTransport}}

    return nil
}

You can see that I have a tlsConfig. My question is how do I incorporate this tlsConfig into my Client?

Upvotes: 1

Views: 1356

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79604

You handle this by calling the original/default transport in your RoundTrip method, which you're already doing:

return t.underlyingTransport.RoundTrip(req)

So you just have to configure it properly:

Client = &http.Client{Transport: &customTransport{underlyingTransport: http.DefaultTransport}}

Which you're also already doing.

The only thing you need to change is that you should use a transport using your TLS config, rather than http.DefaultTransport:

transport := &http.Transport{
    TLSClientConfig: tlsConfig,
}
Client = &http.Client{Transport: &customTransport{underlyingTransport: transport}}

Upvotes: 2

Related Questions