Skip to content

Instantly share code, notes, and snippets.

@ninedraft
Last active December 27, 2018 16:26
Show Gist options
  • Save ninedraft/a7867051984929212dd0ac15eea43bd1 to your computer and use it in GitHub Desktop.
Save ninedraft/a7867051984929212dd0ac15eea43bd1 to your computer and use it in GitHub Desktop.
simple factory to build http.Client over SOCKS5 proxy
import (
"net"
"net/http"
"time"
"golang.org/x/net/proxy"
)
type Auth = proxy.Auth
var NoAuth = Auth{}
// use NoAuth as authData in case if no authentication required
// In that case proxy.SOCKS5 expects nil, not &proxy.Auth{},
// or else emits error "invalid username/password"
func SOCKS5(proxyAddr string, authData Auth) (*http.Client, error) {
const timeout = 5 * time.Second
var auth *proxy.Auth
if authData != NoAuth {
auth = &authData
}
var tcpDialer = &net.Dialer{
Timeout: timeout,
}
var proxyDialer, errSOCKS5 = proxy.SOCKS5("tcp", proxyAddr, auth, tcpDialer)
if errSOCKS5 != nil {
return nil, errSOCKS5
}
return &http.Client{
Timeout: 2 * timeout,
Transport: &http.Transport{
Dial: proxyDialer.Dial,
},
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment