How to use a proxy in Go with net/http
Go's standard library supports HTTP and SOCKS5 proxies out of the box: set Transport.Proxy to http.ProxyURL(...) and you're done. This guide covers authentication, rotating and sticky IPs, country targeting, SOCKS5, running many goroutines safely, and reading proxy errors from the CONNECT response.
Updated 9 November 2026
Prerequisites
- Go 1.20 or newer (for
OnProxyConnectResponse; everything else works on older versions). No third-party modules needed. - A proxy login from the dashboard under Logins, written as
USERandPASS.
Typical uses: uptime and content monitoring from several regions, price tracking, and data pipelines that collect public data.
Basic HTTP proxy
Build an http.Transport with Proxy: http.ProxyURL(u) and use it in your client. For HTTPS targets Go opens a CONNECT tunnel, so TLS stays end to end; for HTTP targets it forwards the request. Reuse the client: transports are safe for concurrent use and pool connections.
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"time"
)
func main() {
proxyURL, err := url.Parse("http://USER-cc-us:PASS@gw.hyperproxy.io:8888")
if err != nil {
log.Fatal(err)
}
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
Timeout: 30 * time.Second,
}
res, err := client.Get("https://api.ipify.org")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body)) // the exit IP
}http.DefaultTransport already uses http.ProxyFromEnvironment, so HTTPS_PROXY=http://USER:PASS@gw.hyperproxy.io:8888 also works without code changes. An explicit transport is easier to reason about.
Authentication
If the proxy URL has a userinfo part, Go sends it as a Proxy-Authorization header (for SOCKS5, in the handshake). Build the URL with url.UserPassword(user, pass) rather than string formatting, so special characters in the password are encoded correctly.
Rotating vs sticky IPs
The gateway gives every new connection a new exit. Go keeps connections alive, so requests to the same host through one transport usually share an exit. Set DisableKeepAlives: true to get a new IP per request. For multi-step work, add a session id to the username: same id, same exit, for 5 minutes by default or up to 120 with ttl.
// No keep-alive: every request opens a new connection, so every request gets a new exit.
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
DisableKeepAlives: true,
}
client := &http.Client{Transport: transport, Timeout: 30 * time.Second}Country and city targeting
| Username | Exit |
|---|---|
USER-cc-us | United States |
USER-cc-us-city-new_york | New York |
USER-cc-us-region-california | California |
USER-cc-de-asn-3320 | One German network |
USER-cont-eu | Anywhere in Europe |
USER-cc-us-city-houston-strict-false | Houston, falling back to the US |
To pick a country per request with one client, set Transport.Proxy to a function that reads the country from the request context and returns the matching URL. Options: Targeting.
SOCKS5
Transport.Proxy accepts socks5:// and socks5h:// URLs with credentials. Go sends the hostname to the proxy in both cases (the docs say socks5 is treated like socks5h), so DNS is resolved on the exit side. You don't need golang.org/x/net/proxy for this.
// No extra packages: net/http speaks SOCKS5 itself.
proxyURL, _ := url.Parse("socks5h://USER-cc-de:PASS@gw.hyperproxy.io:8888")
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
Timeout: 30 * time.Second,
}Concurrency
Share one client across goroutines, bound the number in flight with a semaphore channel or errgroup.SetLimit, and cap connections with MaxConnsPerHost. Always drain and close response bodies, or connections leak.
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxConnsPerHost: 10,
MaxIdleConnsPerHost: 10,
}
client := &http.Client{Transport: transport, Timeout: 30 * time.Second}
sem := make(chan struct{}, 10) // at most 10 requests in flight
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
res, err := client.Get(fmt.Sprintf("https://example.com/page/%d", i))
if err != nil {
log.Println(i, err)
return
}
io.Copy(io.Discard, res.Body) // drain so the connection can be reused
res.Body.Close()
log.Println(i, res.StatusCode)
}(i)
}
wg.Wait()Error handling and retries
When the gateway refuses a CONNECT, client.Get returns an error with only the reason text, for example Proxy Authentication Required. Since Go 1.20, OnProxyConnectResponse lets you turn the status into a typed error. Plain HTTP targets return the status as a normal response. Codes, from Errors:
- 407: wrong login, an invalid or repeated option, or no balance. Don't retry.
- 404: no exit matches; widen the targeting or add
strict-false. - 403: the target is not allowed. 400: a malformed request.
- 429: back off. 502 / 504: retry; without a session each retry gets a new exit.
// ProxyStatusError carries the gateway's answer to CONNECT (HTTPS targets).
type ProxyStatusError struct{ Code int }
func (e *ProxyStatusError) Error() string { return fmt.Sprintf("proxy CONNECT returned %d", e.Code) }
func newClient(proxyURL *url.URL) *http.Client {
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
// Go 1.20+: inspect the CONNECT response before the tunnel is used
OnProxyConnectResponse: func(_ context.Context, _ *url.URL, _ *http.Request, res *http.Response) error {
if res.StatusCode != http.StatusOK {
return &ProxyStatusError{Code: res.StatusCode}
}
return nil
},
}
return &http.Client{Transport: transport, Timeout: 30 * time.Second}
}
func get(client *http.Client, target string) (*http.Response, error) {
var lastErr error
for attempt := 0; attempt < 4; attempt++ {
res, err := client.Get(target)
var pe *ProxyStatusError
switch {
case errors.As(err, &pe) && pe.Code != 429 && pe.Code != 502 && pe.Code != 504:
return nil, err // 400, 403, 404, 407: fix the request, don't retry
case err == nil && res.StatusCode != 429 && res.StatusCode != 502 && res.StatusCode != 504:
return res, nil
case err == nil:
res.Body.Close()
lastErr = fmt.Errorf("status %d", res.StatusCode)
default:
lastErr = err
}
time.Sleep(time.Duration(1<<attempt) * time.Second) // new exit unless sticky
}
return nil, lastErr
}Verify the exit IP
Run the basic program: it prints the IP https://api.ipify.org sees. With DisableKeepAlives a loop of requests prints a different IP each time; a sticky client prints the same one.
Troubleshooting
- Error "Proxy Authentication Required": check credentials, balance and option spelling.
- The proxy is ignored: you set
Proxyon a transport the client doesn't use, orNO_PROXYmatches when usingProxyFromEnvironment. - Same IP for every request: keep-alive; disable it or use a new session id.
- Requests hang: set
Client.Timeoutor use a context with a deadline.
FAQ
Do I need golang.org/x/net/proxy?
Not for HTTP clients; net/http handles SOCKS5 itself. That package is useful when you need a raw SOCKS5 net.Conn for other protocols.
Is http.Transport safe to share between goroutines?
Yes. Create it once and reuse it; creating a transport per request wastes connections.
Does this work with Colly or other Go scrapers?
Most Go scrapers sit on net/http and accept a proxy URL or transport. Colly, for example, has SetProxy.
Where are more examples?
See Examples and the curl guide for testing from the command line.
Try it on your own workload
Sign up with GitHub or Google, create a proxy login and send your first request in a minute.
More proxy integration guides
- Python requests — Rotating and sticky residential proxies with Python requests, including SOCKS5 and retries.
- Python httpx — Sync and async httpx through a residential proxy with the proxy= argument and SOCKS5.
- Python aiohttp — High-concurrency aiohttp requests through rotating or sticky residential IPs.
- Scrapy — Route Scrapy spiders through residential proxies with request.meta and a middleware.
- Playwright — Run Playwright through residential proxies, per browser or per context, with sticky sessions.
- Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
- Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
- Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
- Node.js fetch & undici — Use Node's built-in fetch with undici ProxyAgent or NODE_USE_ENV_PROXY.
- curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.