Sending Go net/http requests through an authenticated proxy
By the ProxyV4 Engineering Team · Updated:
In Go, the proxy belongs to the http.Transport: set Transport.Proxy to http.ProxyURL(u), where u is a parsed http://USER:PASS@IP:PORT URL, and wrap that transport in an http.Client. Go reads the credentials from the URL and sends Proxy-Authorization itself. The same field accepts socks5:// URLs, so SOCKS5 needs no extra module in current Go releases.
A complete program in twenty lines
Start from something that runs. This program sends one HTTPS request through an authenticated HTTP proxy and prints the exit IP:
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"time"
)
func main() {
proxyURL := &url.URL{
Scheme: "http",
User: url.UserPassword("USER", "PASS"),
Host: "203.0.113.10:8080",
}
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
Timeout: 20 * time.Second,
}
resp, err := client.Get("https://proxyv4.com/api/my-ip")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(resp.Status, string(body))
}Two choices in that snippet are deliberate. Building the URL with a struct and url.UserPassword avoids escaping bugs, because a password containing @ or / would break url.Parse("http://USER:PASS@..."). And http.Client.Timeout bounds the whole request, which matters with proxies because a stalled tunnel otherwise blocks a goroutine indefinitely.
How Go authenticates to the proxy
When the proxy URL carries userinfo, the transport adds a Basic Proxy-Authorization header in two places: on forwarded plain-HTTP requests and on the CONNECT request it sends before an HTTPS tunnel. You do not need to set the header yourself, and you should not set it on req.Header for HTTPS targets, because those headers travel inside the encrypted tunnel where the proxy never sees them.
Extra headers on CONNECT
If a proxy needs other headers during tunnel setup, use Transport.ProxyConnectHeader for a fixed set or Transport.GetProxyConnectHeader to compute them per proxy and target. Plain proxy logins never need this; it exists for gateways that take routing hints in headers.
Cloning the default transport
A bare &http.Transport{} lacks the dial timeouts, idle-connection limits and HTTP/2 settings of http.DefaultTransport. In production, clone the default and override only the proxy:
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = http.ProxyURL(proxyURL)
client := &http.Client{Transport: tr, Timeout: 20 * time.Second}Golang SOCKS5 proxy: built in or x/net/proxy
Transport.Proxy understands four schemes: http, https, socks5 and socks5h. Go treats socks5 and socks5h the same way, handing the hostname to the proxy for resolution. For most programs, SOCKS5 is just a different scheme in the URL:
proxyURL := &url.URL{
Scheme: "socks5",
User: url.UserPassword("USER", "PASS"),
Host: "203.0.113.10:1080",
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = http.ProxyURL(proxyURL)The golang.org/x/net/proxy package is still useful when you need a SOCKS5 dialer outside net/http, for example for a raw TCP protocol, or when you want to chain dialers. It returns a dialer you plug into DialContext; in that case leave Proxy nil so the two mechanisms do not stack:
import "golang.org/x/net/proxy"
dialer, err := proxy.SOCKS5("tcp", "203.0.113.10:1080",
&proxy.Auth{User: "USER", Password: "PASS"}, proxy.Direct)
if err != nil {
panic(err)
}
tr := &http.Transport{
Proxy: nil,
DialContext: dialer.(proxy.ContextDialer).DialContext,
}Fetch the module with go get golang.org/x/net/proxy. Which protocol to use is mostly a matter of what your proxy port speaks; the differences are explained in HTTP vs SOCKS5.
Choosing a Go transport proxy per request
Transport.Proxy is a function, func(*http.Request) (*url.URL, error), so http.ProxyURL is only the simplest implementation. Write your own and you can pick the proxy from the request, for instance from a value stored in its context:
type proxyKey struct{}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = func(r *http.Request) (*url.URL, error) {
if u, ok := r.Context().Value(proxyKey{}).(*url.URL); ok {
return u, nil
}
return nil, nil // no proxy: connect directly
}
client := &http.Client{Transport: tr}
// proxyB is another *url.URL built like proxyURL above
ctx := context.WithValue(context.Background(), proxyKey{}, proxyB)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/", nil)
resp, err := client.Do(req)The transport keys its idle connections by proxy, so connections opened through one IP are never reused for a request meant for another. That makes a single shared transport safe for many exits. The alternative, one http.Client per IP, is easier to reason about when each worker owns a fixed address; both approaches are valid.
HTTP_PROXY, HTTPS_PROXY and NO_PROXY in Go
http.DefaultTransport, and therefore http.Get and the zero-value http.Client, uses http.ProxyFromEnvironment. It reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or their lowercase forms) and picks the variable matching the target's scheme. A value without a scheme, such as 203.0.113.10:8080, is treated as http://.
Three behaviors cause most surprises:
- The environment is read once and cached for the life of the process, so changing
os.Setenvafter the first request has no effect. - Requests to
localhostare never proxied byProxyFromEnvironment, even withoutNO_PROXY. - Setting
Transport.Proxyyourself replaces the environment lookup completely. To combine both, callhttp.ProxyFromEnvironment(r)inside your own function as a fallback.
One transport per private IPv4
Go services that need a proxy are usually workers: scrapers, API pollers, monitoring probes or integrations whose partner only accepts traffic from known addresses. They benefit from a fixed exit IP, because the same address appears on every request and every restart. A ProxyV4 private IPv4 is a straightforward fit. Each order line ip:port:user:pass maps to one url.URL, each IP has a single tenant for the whole term, and the same IP stays yours while the proxy is active and after renewal.
Every paid proxy supports HTTP(S), and private IPv4 outside Vietnam and US static ISP proxies also support SOCKS5 with username and password, and you can enable both on one port from the order page, so the http and socks5 examples above work against the same line. Switching modes can move the proxy to a new port, so copy the line again afterwards. Traffic is unmetered on private IPv4 and static ISP. For crawl sizing, see the web scraping proxy guide; current per-IP prices fall as the order grows, and a single IP is a valid order.
It does not fit a design that needs a new IP on every request, since rotating proxies are not on sale, nor targets that only accept mobile IPs. IPv6 proxies are a separate product that only works on IPv6-ready sites. If your service relies on UDP, ask support through a ticket before ordering.
Proxy errors Go returns, and what they mean
Go's proxy errors are terse, but the prefix of the message tells you which stage failed. Wrap them with errors.As against *url.Error and *net.OpError if you need to branch in code.
proxyconnect tcp: connection refused or i/o timeout
Get "https://example.com": proxyconnect tcp: dial tcp 203.0.113.10:8080: connect: connection refused means Go could not open a TCP connection to the proxy. The address or port is wrong, the port moved after a protocol change, or outbound traffic is blocked. An i/o timeout at the same stage points at the network path. Check the port with the port checker.
Proxy Authentication Required
For an HTTPS target, a failed login returns an error whose text is just the status phrase: Get "https://example.com": Proxy Authentication Required. For a plain HTTP target you get a normal *http.Response with StatusCode == 407 and no error, so check the status code too. Confirm the user and password, and that the URL was built with url.UserPassword rather than string concatenation. The 407 error guide lists other causes.
SOCKS errors
SOCKS failures mention socks connect and the target, for example an authentication failure or a general server failure reply. A socks5:// URL aimed at an HTTP-only port typically fails during the handshake, so confirm which mode the port is in.
Frequently asked questions
Why does my Go program ignore HTTPS_PROXY?
Either you built a Transport without setting Proxy, which means no proxy at all, or the variable was set after the first request and the cached value is used. Set Proxy: http.ProxyFromEnvironment explicitly and export the variable before the process starts.
Do I still need golang.org/x/net/proxy for SOCKS5?
Not for net/http. Transport.Proxy accepts socks5:// and socks5h:// URLs with credentials. Use x/net/proxy when you need a SOCKS dialer for non-HTTP connections.
Is it safe to share one http.Client across goroutines with a proxy?
Yes. http.Client and http.Transport are safe for concurrent use, and connections are pooled per proxy, so share them rather than creating a client per request.
Can I use one ProxyV4 IP for both HTTP and SOCKS5 in Go?
Yes. Choose both modes on the order page and the same port accepts either protocol, so only the scheme in your url.URL changes.
How do I confirm the exit IP from Go?
Request an IP echo endpoint through the client, as in the first example, and compare it with the IP in your proxy line. The proxy checker gives the same answer without code.
One ip:port:user:pass line per Go transport
ProxyV4 private IPv4 proxies work with Go over HTTP or SOCKS5 with a username and password, keep the same address when you renew, and never meter traffic. Start with one IP and point a transport at it.
Try one private IP