Skip to content

Instantly share code, notes, and snippets.

@fengjijiao
Forked from ometa/socks5_proxy.go
Created April 23, 2022 04:04
Show Gist options
  • Select an option

  • Save fengjijiao/8015cd99e0bdc2e5037f905fab2a6541 to your computer and use it in GitHub Desktop.

Select an option

Save fengjijiao/8015cd99e0bdc2e5037f905fab2a6541 to your computer and use it in GitHub Desktop.
Golang HTTP Client using SOCKS5 proxy and DialContext
// 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