在Golang中绕过http_proxy

I have env variable set for http_proxy, but with another call, I like to bypass proxy and use direct connection to destination server instead.

Is there any way I can do that in Go lang?

Thanks.

As @Volker mentioned, you can either:

  • Use your own RoundTripper instead of the DefaultTransport
  • Modify DefaultTransport.Proxy to return nil for the request in question
  • If the call you want to ignore proxies with is to a specific host, and you always want to ignore proxy for calls to that host, add the host to the NO_PROXY environment variable

this is what I did:

var defaultTransport http.RoundTripper = &http.Transport{
    Proxy: nil,
    DialContext: (&net.Dialer{
        Timeout:   10 * time.Second,
        KeepAlive: 30 * time.Second,
        DualStack: true,
    }).DialContext,
    MaxIdleConns:          30,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   15 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

client := &http.Client{Transport: defaultTransport}