-
-
Save cute-angelia/ae09fa2e856f2fca0cb0cdaaad934f02 to your computer and use it in GitHub Desktop.
Golang HTTP Client using SOCKS5 proxy and DialContext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Golang example that creates an http client that leverages a SOCKS5 proxy and a DialContext | |
func NewClientFromEnv() (*http.Client, error) { | |
proxyHost := os.Getenv("PROXY_HOST") | |
baseDialer := &net.Dialer{ | |
Timeout: 30 * time.Second, | |
KeepAlive: 30 * time.Second, | |
} | |
var dialContext DialContext | |
if proxyHost != "" { | |
dialSocksProxy, err := proxy.SOCKS5("tcp", proxyHost, nil, baseDialer) | |
if err != nil { | |
return nil, errors.Wrap(err, "Error creating SOCKS5 proxy") | |
} | |
if contextDialer, ok := dialSocksProxy.(proxy.ContextDialer); ok { | |
dialContext = contextDialer.DialContext | |
} else { | |
return nil, errors.New("Failed type assertion to DialContext") | |
} | |
logger.Debug("Using SOCKS5 proxy for http client", | |
zap.String("host", proxyHost), | |
) | |
} else { | |
dialContext = (baseDialer).DialContext | |
} | |
httpClient = newClient(dialContext) | |
return httpClient, nil | |
} | |
func newClient(dialContext DialContext) *http.Client { | |
return &http.Client{ | |
Transport: &http.Transport{ | |
Proxy: http.ProxyFromEnvironment, | |
DialContext: dialContext, | |
MaxIdleConns: 10, | |
IdleConnTimeout: 60 * time.Second, | |
TLSHandshakeTimeout: 10 * time.Second, | |
ExpectContinueTimeout: 1 * time.Second, | |
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment