Sending Go net/http requests through an authenticated proxy

· 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.

One ip:port:user:pass line per Go transport

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.Setenv after the first request has no effect.
  • Requests to localhost are never proxied by ProxyFromEnvironment, even without NO_PROXY.
  • Setting Transport.Proxy yourself replaces the environment lookup completely. To combine both, call http.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

Related articles

Proxy setup
Using cURL with an authenticated proxy: commands that prove it works
Send cURL requests through an authenticated HTTP(S) proxy with -x and -U, confirm the exit IP, read the CONNECT handshake and time each request on any OS.
Knowledge base
HTTP or SOCKS5: Picking the Proxy Protocol Your Software Needs
HTTP vs SOCKS5 proxy in plain terms: what each protocol carries, why HTTPS works through both, where UDP matters, and how to test which one a server speaks.
Free tools
Check proxies in bulk: status, exit IP and latency
Free online proxy checker: paste up to 100 ip:port:user:pass lines and see which proxies work, their exit IP and latency, plus what each failure result means.
Proxies by platform
Proxies for web scraping: a fixed pool of IPs with unmetered traffic
Web scraping proxies for Python, Scrapy, Playwright and Selenium: a pool of private IPv4 and static ISP addresses, unlimited bandwidth, flat per-IP pricing.
Products
Dedicated datacenter proxies: one private IPv4 per customer
Private IPv4 proxies in the US, Vietnam, Japan, South Korea, Singapore, the UK and Hong Kong. One tenant per IP, HTTP(S) and SOCKS5, no traffic metering.
Proxy setup
Set up your proxy, tool by tool
Proxy setup instructions you can follow with the dashboard open: antidetect browsers, operating systems, browser extensions and scraping libraries, all with authenticated HTTP(S) or SOCKS5.
Knowledge base
Getting Java's HttpClient to authenticate to a proxy
Java HttpClient proxy authentication that works for HTTPS: the Authenticator, the disabledSchemes property that blocks Basic, OkHttp and SOCKS options.
Knowledge base
Configuring a proxy for HttpClient in C# and .NET
Route C# HttpClient proxy traffic with WebProxy and NetworkCredential, use SOCKS5 on .NET 6+, give each IHttpClientFactory client its own IP and fix 407s.
Knowledge base
Sending PHP cURL Requests Through an Authenticated Proxy
Set up a PHP cURL proxy with CURLOPT_PROXYUSERPWD, switch to SOCKS5 with socks5h, configure Guzzle's proxy option and decode the errors cURL returns.
Products
Static ISP proxies: residential IPs on consumer networks
Static ISP proxies in the United States and Vietnam: fixed IPs registered to consumer internet providers, rented to one customer, with unmetered traffic.