Originally published on proxymint.
Golang HTTP client proxy setup with net/http: Transport.Proxy, user:pass auth, SOCKS5 without extra packages, env variables, pooling per proxy and rotation.
TL;DR
- Set Transport.Proxy to http.ProxyURL and you're done for a fixed proxy. Build the URL with url.UserPassword so symbols in the password survive, and reuse the client, because the transport holds the connection pool.
- You don't need golang.org/x/net/proxy for SOCKS5 in net/http. Transport.Proxy has taken socks5:// since Go 1.9, with the login from the URL, and it sends the hostname to the proxy, so DNS resolves there.
- If your HTTPS_PROXY is ignored, check whether you built a fresh http.Transport. Only DefaultTransport and its clones read the environment, which catches people constantly, so clone the default instead of starting from zero.
- Same IP on every request through a rotating gateway is usually keep-alive. One pooled CONNECT tunnel is one TCP connection from one exit, so test with DisableKeepAlives before you blame the proxy.
Key takeaways
- Put proxy headers on the transport, not the request. A Proxy-Authorization header set with req.Header never reaches the CONNECT for an https:// URL, so you get Proxy Authentication Required with a correct password; ProxyConnectHeader or user info in the URL fixes it.
- Wire OnProxyConnectResponse in (Go 1.20 and later). Without it a refused CONNECT is a bare error with the proxy's reason phrase and no status code, which makes 407 and 502 hard to tell apart in code.
- Raise MaxIdleConnsPerHost for crawlers. The default of 2 closes most connections after use when many goroutines hit one host, and each closed one costs a new tunnel and TLS handshake.
- Check rotation with an https:// echo endpoint, pooled and unpooled. Compare the counts of distinct exits with keep-alive on and off against a direct call, and you'll know whether rotation or your pool decides the IP.
Read the full guide on proxymint, with the commands, tables and sources.
Top comments (0)