Golang HTTP client proxy: auth, SOCKS5, pooling, rotation

Golang HTTP client proxy setup with net/http: Transport.Proxy, user:pass auth, SOCKS5 without extra packages, env variables, pooling per proxy and rotation.

A white http.Transport module marked Go 1.26: its code well reads Proxy: http.ProxyURL(u), two teal keys take http:// and socks5://, same field, no extra package, and its idle pool, keyed by the proxy URL, holds one open CONNECT tunnel and one free slot. The tunnel runs from its side into a graphite proxy unit, rotating gateway, and on to the echo page api.ipify.org, which reads same exit IP on every request. A gold note wired into the Transport gives the fix: DisableKeepAlives: true, five requests, five CONNECTs, a new tunnel per request.
Quick summary · TL;DR
  1. 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.
  2. 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.
  3. 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.
  4. 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.

If you need a golang HTTP client proxy, build an http.Transport whose Proxy field is http.ProxyURL(u), where u is a *url.URL like http://USERNAME:PASSWORD@HOST:PORT, and hand that transport to an http.Client. Credentials in the URL go out as a Basic Proxy-Authorization header, HTTPS targets travel through a CONNECT tunnel, and socks5:// works in the same field with no extra package.

Getting the first request through is the easy part, and the odd stuff comes after. A brand-new &http.Transport{} quietly ignores the HTTPS_PROXY you exported, a Proxy-Authorization header you set on the request still ends in Proxy Authentication Required, and a rotating gateway hands every request in a run the same IP because the client kept one tunnel open.

Most of the pages that rank for this also tell you SOCKS5 needs golang.org/x/net/proxy. That stopped being true in Go 1.9. Everything below was checked against the net/http transport source at the go1.26.0 tag (read November 9, 2026), and every snippet builds on Go 1.26.

Golang HTTP client proxy setup

For a fixed proxy, this is the whole go http client proxy setup:

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"time"
)

func main() {
	proxyURL := &url.URL{
		Scheme: "http",
		User:   url.UserPassword("USERNAME", "PASSWORD"),
		Host:   "HOST:PORT",
	}

	client := &http.Client{
		Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
		Timeout:   30 * time.Second,
	}

	resp, err := client.Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(resp.StatusCode, string(body))
}

Build the URL with url.UserPassword rather than gluing a string together. It escapes @, : and / in the password for you, which matters when a provider generates passwords with symbols in them.

A proxy can reach a Go client in four ways, and it helps to know which one you’re on before debugging anything:

How the proxy is setWhere it livesWhat it covers
http.ProxyURL(u)Transport.ProxyOne fixed proxy for every request on that transport
http.ProxyFromEnvironmenthttp.DefaultTransport and its clonesHTTP_PROXY, HTTPS_PROXY, NO_PROXY
Your own func(*http.Request) (*url.URL, error)Transport.ProxyA proxy picked per request: rotation, per-host routing
A SOCKS dialer from golang.org/x/net/proxyTransport.DialContextEvery TCP connection the transport opens, plus non-HTTP traffic

Reuse the client. An http.Client and its transport are safe for concurrent use, and the transport holds the connection pool. Building a new transport per request throws the pool away, so every call pays for a fresh TCP connect, a CONNECT and a TLS handshake.

Proxy username and password in net/http

When the proxy URL carries user info, the transport turns it into Proxy-Authorization: Basic ... itself. It does this up front. The first CONNECT already carries the header, so there’s no 407 challenge followed by a retry, which is what .NET’s handler does (see the C# HttpClient proxy guide for that one). Point five HTTPS requests from one client at a logging proxy and it shows a single CONNECT, with the header already on it.

Go only does Basic here. Corporate proxies that answer with Proxy-Authenticate: NTLM or Negotiate won’t accept it, and the 407 Proxy Authentication Required guide covers how to tell those cases apart.

Passwords with @ or :

If you parse a raw string instead, url.Parse("http://user:p@ss@HOST:PORT") still works, because the parser splits user info at the last @. A /, ? or # in the password breaks it, though, with an error like invalid port ":p" after host that points nowhere near the password. That’s an easy one to miss when the password was pasted from a host:port:user:pass export. Percent-encode those (%2F, %3F, %23) or use url.UserPassword, and the proxy string formats guide shows how to turn each export layout into a URL.

HTTPS targets and the CONNECT tunnel

Most of the header confusion comes from how the transport treats the two target schemes.

  • http:// target: the request goes to the proxy in absolute form (GET http://example.com/ HTTP/1.1) and the transport adds Proxy-Authorization to that request. Every plain-HTTP host shares the same pooled connections to the proxy.
  • https:// target: the transport sends CONNECT example.com:443, waits for a 200, then runs TLS to the target inside the tunnel. The proxy never sees the request headers, and your headers never reach the proxy.

That second point explains a common bug. Setting req.Header.Set("Proxy-Authorization", ...) works for http:// URLs and fails for https:// ones with Proxy Authentication Required, because the header rides inside the tunnel and the CONNECT goes out without it. Headers meant for the proxy belong on the transport:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/url"
)

func main() {
	proxyURL, err := url.Parse("http://HOST:PORT")
	if err != nil {
		log.Fatal(err)
	}
	tr := &http.Transport{
		Proxy: http.ProxyURL(proxyURL),
		// Sent on every CONNECT, for https:// targets only.
		ProxyConnectHeader: http.Header{"X-Request-Tag": {"crawl-42"}},
		// Called with the proxy's answer to CONNECT, before the 200 check.
		OnProxyConnectResponse: func(ctx context.Context, p *url.URL, req *http.Request, res *http.Response) error {
			if res.StatusCode != http.StatusOK {
				return fmt.Errorf("proxy %s refused CONNECT to %s: %d (%s)",
					p.Host, req.Host, res.StatusCode, res.Header.Get("Proxy-Authenticate"))
			}
			return nil
		},
	}
	resp, err := (&http.Client{Transport: tr}).Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()
}

ProxyConnectHeader arrived in Go 1.8, GetProxyConnectHeader (headers chosen per CONNECT, from a function) in Go 1.16, and OnProxyConnectResponse in Go 1.20. The last one is worth wiring in. Without it, a refused CONNECT reaches your code as a bare error carrying only the proxy’s reason phrase, with no status code to branch on.

SOCKS5 proxy in Go

Since Go 1.9, Transport.Proxy accepts socks5:// URLs, and Go 1.23 added socks5h:// as a synonym. The doc comment on the field says it plainly: “socks5” is treated the same as “socks5h”. User info in the URL becomes an RFC 1929 username and password login (March 1996).

package main

import (
	"log"
	"net/http"
	"net/url"
)

func main() {
	proxyURL := &url.URL{
		Scheme: "socks5", // "socks5h" is accepted from Go 1.23 and behaves the same
		User:   url.UserPassword("USERNAME", "PASSWORD"),
		Host:   "HOST:PORT",
	}
	client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}

	resp, err := client.Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()
}

Go’s bundled dialer sends the target hostname to the proxy as a domain name, so DNS for the target resolves on the proxy side. A logging SOCKS5 server shows address type 3 (domain) and the bare hostname on every connection, never a resolved IP. That’s the opposite of curl and Python’s requests, where plain socks5:// resolves locally and only socks5h:// hands the name over, and the DNS leak guide goes through each client. On the proxymint gateway, Lab #1 measured that CONNECT and remote-DNS SOCKS requests carrying a hostname are resolved proxy side.

A wrong SOCKS password comes back as socks connect tcp 127.0.0.1:PORT->example.com:443: username/password authentication failed, which at least names the hop.

When golang.org/x/net/proxy still helps

The x/net proxy package (v0.62.0, checked November 9, 2026) is still the right tool when the thing you’re proxying isn’t net/http: a raw TCP client, a gRPC dial, an SMTP check. Its SOCKS5 function returns a Dialer, and the value it returns also implements ContextDialer, which is the shape Transport.DialContext wants:

package main

import (
	"context"
	"log"
	"net/http"

	"golang.org/x/net/proxy"
)

func main() {
	auth := &proxy.Auth{User: "USERNAME", Password: "PASSWORD"}
	dialer, err := proxy.SOCKS5("tcp", "HOST:PORT", auth, proxy.Direct)
	if err != nil {
		log.Fatal(err)
	}
	ctxDialer, ok := dialer.(proxy.ContextDialer)
	if !ok {
		log.Fatal("dialer does not support DialContext")
	}

	tr := &http.Transport{
		Proxy:       nil, // the dialer is the proxy now
		DialContext: ctxDialer.DialContext,
	}
	resp, err := (&http.Client{Transport: tr}).Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()

	// The same dialer works for traffic that is not HTTP.
	conn, err := ctxDialer.DialContext(context.Background(), "tcp", "example.com:443")
	if err == nil {
		conn.Close()
	}
}

Leave Proxy nil when the dialer does the proxying. If you clone http.DefaultTransport and then set DialContext, the clone still carries ProxyFromEnvironment, and an exported HTTPS_PROXY would send a CONNECT down the SOCKS tunnel, which is a confusing failure to debug at 2 a.m.

Environment variables and ProxyFromEnvironment

http.DefaultTransport, which is what http.Get and a zero http.Client{} use, sets Proxy: http.ProxyFromEnvironment. Your own transport does not. So &http.Transport{TLSClientConfig: cfg} ignores HTTPS_PROXY completely, and it’s the first thing to check when a Go client seems to ignore your proxy. If you want the environment honoured with your own settings, clone the default:

package main

import (
	"log"
	"net/http"
	"time"
)

func main() {
	// Keeps Proxy: http.ProxyFromEnvironment and the default pool settings.
	tr := http.DefaultTransport.(*http.Transport).Clone()
	tr.MaxIdleConnsPerHost = 16

	client := &http.Client{Transport: tr, Timeout: 30 * time.Second}
	resp, err := client.Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()
}

Six rules from the httpproxy package that the default uses (go1.26.0 tag, read November 9, 2026):

  1. Go reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY and checks the uppercase name before the lowercase one. With both set, HTTPS_PROXY wins, while curl looks at the lowercase name first, so a machine with two different values behaves differently in each tool.
  2. There’s no ALL_PROXY support in net/http. A socks5:// value in HTTPS_PROXY works, though.
  3. The variables are read once per process. Changing them with os.Setenv after the first request has no effect.
  4. localhost and loopback addresses are never proxied from the environment, so a local test server bypasses the proxy even with NO_PROXY empty. http.ProxyURL has no such exception.
  5. When REQUEST_METHOD is set (a CGI process), Go refuses to use HTTP_PROXY for http:// requests and returns an error that points at golang.org/s/cgihttpproxy.
  6. NO_PROXY takes comma-separated hosts, IP prefixes and CIDR ranges, with optional ports. example.com matches the domain and its subdomains, .example.com matches subdomains only, and * turns the proxy off.

User info in the variable works and is percent-decoded, so HTTPS_PROXY=http://user:p%40ss@HOST:PORT logs in with the password p@ss.

Connection pooling per proxy

In a golang HTTP client proxy setup, the pool decides which exit you see. The transport keys its idle pool on the full proxy URL, user info included, plus the target scheme and address. Two practical results follow from that, and both change what a rotating proxy looks like from your side.

One open tunnel means one exit. A CONNECT tunnel is a single TCP connection from the proxy’s exit to the target. With keep-alive on (the default), later requests to the same host reuse it, so a burst of requests leaves from one IP no matter how the proxy rotates. Five requests on one client go through one CONNECT.

Different credentials mean different pools. Two proxy URLs that differ only in the username never share a connection, so one login’s tunnels can’t be reused by accident for another.

Reuse is controlled by a handful of fields:

  • DisableKeepAlives: true closes each connection after one request, so every request gets a new tunnel (five requests, five CONNECTs).
  • tr.CloseIdleConnections() drops the idle pool on demand, for example between two batches.
  • IdleConnTimeout caps how long an idle tunnel waits for reuse (90 seconds on DefaultTransport).
  • MaxIdleConnsPerHost defaults to 2, which is low for a crawler with 50 goroutines on one host. Raise it, or most connections get closed after use instead of pooled.
  • Always read the body to EOF and close it. An unread body keeps the connection out of the pool, which looks like a leak plus a new tunnel per request.

Rotating proxies in Go

There are two shapes, depending on where rotation happens.

You hold a list of proxies. Put the choice in a Proxy func. It runs for each request, and because pools are keyed by proxy URL, each proxy keeps its own warm connections:

package main

import (
	"log"
	"net/http"
	"net/url"
	"sync/atomic"
)

func main() {
	var proxies []*url.URL
	for _, hostPort := range []string{"HOST1:PORT", "HOST2:PORT", "HOST3:PORT"} {
		proxies = append(proxies, &url.URL{
			Scheme: "http",
			User:   url.UserPassword("USERNAME", "PASSWORD"),
			Host:   hostPort,
		})
	}

	var next atomic.Uint64
	tr := &http.Transport{
		// Called once per request. Each proxy URL gets its own idle pool.
		Proxy: func(*http.Request) (*url.URL, error) {
			return proxies[(next.Add(1)-1)%uint64(len(proxies))], nil
		},
		MaxIdleConnsPerHost: 4,
	}
	client := &http.Client{Transport: tr}

	for i := 0; i < 6; i++ {
		resp, err := client.Get("https://api.ipify.org")
		if err != nil {
			log.Println(err)
			continue
		}
		resp.Body.Close()
	}
}

A gateway rotates for you. Then the Go side stays a single http.ProxyURL, and rotation mode is set on the proxy order. On proxymint that’s a new IP on every request, a timer from 5 to 60 minutes, or sticky for as long as the device stays online, and it can be changed later without new credentials. The rotating vs sticky proxies guide covers which jobs break under each. What decides the exit you see in a run is how the gateway’s rotation and your keep-alive interact, and that’s something to measure, not assume.

Colly and resty set the transport for you

Two popular wrappers touch the same Transport.Proxy field, each with one side effect worth knowing.

Colly. c.SetProxy(u) and c.SetProxyFunc(proxy.RoundRobinProxySwitcher(urls...)) both end in the collector’s SetProxyFunc (master branch, read November 9, 2026), which sets DisableKeepAlives = true on the transport. So every Colly request opens a new tunnel, which suits a rotating gateway and costs a TCP connect plus a CONNECT plus a TLS handshake each time. If the collector’s transport isn’t an *http.Transport, Colly replaces it with a bare one, and any timeouts or TLS settings you put on the old one are gone.

resty. client.SetProxy("http://USERNAME:PASSWORD@HOST:PORT") sets http.ProxyURL on resty’s transport. If the string doesn’t parse, resty v2 only logs the error and keeps the proxy setting it already had, which by default is ProxyFromEnvironment. On a machine with no proxy variables, a password with an unescaped / therefore sends your traffic direct, with nothing failing. The exit check below catches that in one run.

Verify the exit IP

This compares a keep-alive client with one that opens a new tunnel per request, next to a direct call:

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"time"
)

const echo = "https://api.ipify.org"

func exit(c *http.Client) string {
	resp, err := c.Get(echo)
	if err != nil {
		return "error: " + err.Error()
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	return string(b)
}

func main() {
	// PROXY_URL=http://USERNAME:PASSWORD@HOST:PORT
	proxyURL, err := url.Parse(os.Getenv("PROXY_URL"))
	if err != nil {
		panic(err)
	}
	newClient := func(keepAlive bool) *http.Client {
		return &http.Client{Timeout: 30 * time.Second, Transport: &http.Transport{
			Proxy:             http.ProxyURL(proxyURL),
			DisableKeepAlives: !keepAlive,
		}}
	}
	direct := &http.Client{Transport: &http.Transport{Proxy: nil}}
	fmt.Println("direct:", exit(direct))

	pooled, fresh := newClient(true), newClient(false)
	pooledExits, freshExits := map[string]bool{}, map[string]bool{}
	for i := 0; i < 20; i++ {
		pooledExits[exit(pooled)] = true
		freshExits[exit(fresh)] = true
	}
	fmt.Println("keep-alive, one tunnel:", len(pooledExits), "distinct exits")
	fmt.Println("new tunnel per request:", len(freshExits), "distinct exits")
}

On an order set to a new IP per request, the first proxied line shows how long connection reuse holds one exit, and the second shows the rotation the order delivers. If the direct line matches either, the proxy isn’t in use. Keep the echo URL on https://: Lab #1 found that the proxymint gateway answers plain http:// requests with a 301 to the https:// URL, which Go follows, so an http:// check ends up measuring something else.

When the proxy fails: Go errors

Proxy faults come back as a *url.Error from client.Get or client.Do. The text after the URL tells you which hop broke. These are the strings Go 1.26 prints:

What went wrongError text after Get "https://...":Check first
Rejected credentials, https:// targetProxy Authentication Required (the proxy’s reason phrase, no code)User info in the proxy URL
Rejected credentials, http:// targetNo error. resp.StatusCode is 407User info in the proxy URL
Proxy port closedproxyconnect tcp: dial tcp HOST:PORT: connect: connection refusedHost and port
SOCKS5 login rejectedsocks connect tcp ...: username/password authentication failedUsername and password
https:// proxy URL on a plain proxy portproxyconnect tcp: tls: first record does not look like a TLS handshake, or proxyconnect tcp: EOFProxy URL scheme
Proxy accepts the connection and never answerscontext deadline exceeded (Client.Timeout exceeded while awaiting headers)Firewall, proxy health

Two timeouts matter here. http.Client.Timeout covers the whole request, including the body read. Inside the transport, the CONNECT exchange has its own fixed one-minute limit, so a proxy that stalls after the TCP connect is cut off even without a client timeout. Set a net.Dialer timeout too, so a dead proxy host fails in seconds.

Across a list of proxies, those errors tell you when to move on. This helper tries each client and skips the ones that fail on the proxy hop:

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"time"
)

type proxyError struct {
	status int
}

func (e *proxyError) Error() string { return fmt.Sprintf("proxy answered CONNECT with %d", e.status) }

func newClient(raw string) (*http.Client, error) {
	u, err := url.Parse(raw)
	if err != nil {
		return nil, err
	}
	tr := &http.Transport{
		Proxy:       http.ProxyURL(u),
		DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
		OnProxyConnectResponse: func(_ context.Context, _ *url.URL, _ *http.Request, res *http.Response) error {
			if res.StatusCode != http.StatusOK {
				return &proxyError{status: res.StatusCode}
			}
			return nil
		},
	}
	return &http.Client{Transport: tr, Timeout: 30 * time.Second}, nil
}

// proxyFault reports whether err happened on the hop to the proxy,
// so the next proxy in the list is worth a try.
func proxyFault(err error) bool {
	var pe *proxyError
	var op *net.OpError
	switch {
	case errors.As(err, &pe):
		return true
	case errors.As(err, &op) && op.Op == "proxyconnect":
		return true
	case errors.Is(err, context.DeadlineExceeded):
		return true
	}
	return false
}

func getWithFailover(clients []*http.Client, target string) (string, error) {
	var errs []error
	for _, c := range clients {
		resp, err := c.Get(target)
		if err != nil {
			if proxyFault(err) {
				errs = append(errs, err)
				continue
			}
			return "", err
		}
		defer resp.Body.Close()
		b, err := io.ReadAll(resp.Body)
		return string(b), err
	}
	return "", errors.Join(errs...)
}

func main() {
	var clients []*http.Client
	for _, raw := range []string{
		"http://USERNAME:PASSWORD@HOST1:PORT",
		"http://USERNAME:PASSWORD@HOST2:PORT",
	} {
		c, err := newClient(raw)
		if err != nil {
			panic(err)
		}
		clients = append(clients, c)
	}
	fmt.Println(getWithFailover(clients, "https://api.ipify.org"))
}

A 403 or 429 from the target is not in that list. It arrives as a normal response with a status code, and switching proxies on it is a decision about the target’s rules, not a proxy fault.

Which proxy fits the Go job

Transport code is identical for every proxy category. What changes is the address that leaves the gateway, and the target decides which one fits.

APIs, monitors and lenient targets at volume: datacenter proxies. This is where most Go services sit: API polling, uptime checks, feeds and bulk collection from sites without anti-bot scoring. Hosting addresses are fast and consistent, IPv4 ports carry no bandwidth cap under normal use, and the pooling settings above (MaxIdleConnsPerHost, keep-alive, reading bodies to EOF) decide most of the throughput you get from each port.

Public pages that treat home users differently (prices, stock, search results by location, ad checks): rotating residential proxies, rotating per request for broad coverage or on a 5 to 60 minute timer when a short session has to hold.

One identity over days (a dashboard login, a partner API that expects one fixed address): static ISP proxies, one ISP-registered address for the whole term.

All three take a username and password over HTTP and SOCKS5. So the golang HTTP client proxy code above, http:// or socks5://, runs unchanged on each of them.

Frequently asked questions

Create an http.Transport with Proxy set to http.ProxyURL(u), where u is the parsed proxy URL such as http://HOST:PORT, and pass it to an http.Client. Reuse that client for every request, since the transport keeps the connection pool. HTTPS URLs then go through a CONNECT tunnel at the proxy.

Put the credentials in the proxy URL, ideally with url.UserPassword("USERNAME", "PASSWORD") so special characters are escaped. net/http turns them into a Basic Proxy-Authorization header and sends it on the first CONNECT, with no 407 round trip. Go does not do NTLM or Negotiate proxy logins on its own.

Yes, since Go 1.9. Set Transport.Proxy to a socks5://USERNAME:PASSWORD@HOST:PORT URL and net/http dials it itself, sending the target hostname to the proxy. Go 1.23 also accepts socks5h://, which behaves the same. golang.org/x/net/proxy is only needed for non-HTTP traffic or a custom dialer.

Only through http.DefaultTransport or a clone of it, which use http.ProxyFromEnvironment. A transport built from scratch ignores HTTP_PROXY and HTTPS_PROXY. The variables are read once per process, the uppercase name is checked first, and localhost and loopback addresses are never proxied from the environment.

With a list of proxies, set Transport.Proxy to a function that returns the next proxy URL for each request; each proxy keeps its own connection pool. With a rotating gateway, keep one fixed proxy URL and set rotation on the proxy order. Keep-alive reuses one tunnel, so disable it or close idle connections when every request needs a fresh exit.

The proxy rejected or never received the credentials on the CONNECT request. Common causes are a Proxy-Authorization header set on the request instead of the transport, a password with a slash, question mark or hash that was not percent-encoded, or a proxy that wants NTLM. For plain http:// targets the 407 arrives as a normal response instead of an error.

Transport.Proxy is a function that receives the *http.Request, so it can choose a proxy from the request's host, a context value or a counter. Connections are pooled per proxy URL, so switching proxies between requests does not mix tunnels. Two clients with separate transports also work when the choice is per job.

Researched and drafted with AI tools, then checked against our publishing rules before it went live: 6 outside links, 9 links to other proxymint pages, no prices and a fact-check pass against our product records. How we write.