How to Use an HTTP Proxy in Go
Go’s HTTP transport can use an explicit proxy or read its proxy settings from the environment. Compare a direct request with a proxied one to check which route your application takes.
Choose where your Go client gets its proxy
Go’s standard net/http package chooses an outgoing proxy in the request transport. There are two common options. Use http.ProxyURL when you want one client to use an explicit proxy. Use http.ProxyFromEnvironment when the service’s deployment should control the route with HTTP_PROXY, HTTPS_PROXY and NO_PROXY. A transport with Proxy set to nil connects directly. Go’s HTTP transport reference
The destination in this guide is the HTTPS IP check at TestMyProxies. A proxy URL starting with http:// describes an ordinary HTTP connection to the proxy. The destination can still use HTTPS if that proxy supports the CONNECT method. The client asks the proxy for a tunnel, then establishes TLS to the destination through it. If the provider instructs you to use TLS to the proxy itself, use its documented https:// proxy URL and the hostname on its certificate. How the proxy and destination protocols differ
Run a Go proxy check and print the exit IP
Save this program as proxycheck.go. It uses only packages from Go’s standard library. The default transport is cloned to give this client its own proxy configuration while retaining the standard transport’s other defaults. The request gets a 15-second deadline that covers connecting, tunneling, waiting for headers and reading the response.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"time"
)
type connectStatus int
func (s connectStatus) Error() string {
return fmt.Sprintf("proxy CONNECT returned HTTP %d", int(s))
}
func check(mode string) error {
const target = "https://testmyproxies.com/api/my-ip"
transport := http.DefaultTransport.(*http.Transport).Clone()
defer transport.CloseIdleConnections()
switch mode {
case "direct":
transport.Proxy = nil
case "env":
transport.Proxy = http.ProxyFromEnvironment
default:
u, err := url.Parse(mode)
if err != nil || u.Hostname() == "" || u.User != nil ||
(u.Scheme != "http" && u.Scheme != "https") {
return errors.New("supply direct, env, or a credential-free HTTP proxy URL")
}
transport.Proxy = http.ProxyURL(u)
}
transport.OnProxyConnectResponse = func(_ context.Context, _ *url.URL,
_ *http.Request, response *http.Response) error {
if response.StatusCode != http.StatusOK {
return connectStatus(response.StatusCode)
}
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return errors.New("could not create the IP-check request")
}
client := &http.Client{
Transport: transport,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Do(req)
if err != nil {
var status connectStatus
switch {
case errors.As(err, &status):
return status
case errors.Is(err, context.DeadlineExceeded):
return errors.New("IP check exceeded the 15-second deadline")
default:
return errors.New("connection failed before a final response; check DNS, TCP and TLS")
}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("IP check returned HTTP %d", resp.StatusCode)
}
var result struct {
IP string `json:"ip"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 8192)).Decode(&result); err != nil {
if ctx.Err() == context.DeadlineExceeded {
return errors.New("IP check exceeded the 15-second deadline while reading the response")
}
return errors.New("IP check returned invalid JSON")
}
if net.ParseIP(result.IP) == nil {
return errors.New("IP check did not return a valid IPv4 or IPv6 address")
}
fmt.Println(result.IP)
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: go run proxycheck.go direct|env|http://proxy.example:3128")
os.Exit(2)
}
if err := check(os.Args[1]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
On a network where direct requests are allowed, get a baseline first. For the second command, replace proxy.example:3128 with your proxy’s host and port. Use an endpoint that accepts requests from your source IP or is otherwise set up for a credential-free check.
go run proxycheck.go direct
go run proxycheck.go http://proxy.example:3128
Each successful run prints the IPv4 or IPv6 address observed by the IP endpoint. Compare the second address with your provider’s expected exit. The exit often differs from the proxy gateway’s address. A rotating endpoint can select different exits, so compare a pinned session or the provider’s documented exit pool when available. Run from the same host or container as the real workload. A proxy check from your laptop can succeed even when a server or container has a different DNS resolver, route or source IP. Check the same request inside Docker
The example leaves redirects unfollowed so each run checks the same destination. It reports the first HTTP status even if that response points elsewhere. For other errors, it prints the stage or a short diagnostic without dumping private proxy settings. In your own app, record the error type and destination alongside timing so an operator can trace a failure without exposing the proxy URL or credentials. Go’s redirect handling reference
Use HTTPS_PROXY and NO_PROXY in a Go process
For an HTTPS destination, configure HTTPS_PROXY. The value can still start with http:// if your connection to the proxy is unencrypted. This command supplies a proxy and a short bypass list to a single Go invocation in a POSIX shell. Adjust the bypass list to match your deployment.
HTTPS_PROXY=http://proxy.example:3128 NO_PROXY=localhost,127.0.0.1 go run proxycheck.go env
ProxyFromEnvironment also accepts lowercase variable names and automatically bypasses localhost and loopback addresses. A NO_PROXY match sends a request directly. Check whether a broad entry such as * covers the test destination. ProxyURL returns the proxy you supplied for each request and does not consult the environment bypass list. When testing a change to the environment, start a new process. The standard library caches its environment-based proxy function after the first time it is needed. Go’s environment proxy documentation and Go transport source
For a service that uses HTTP Basic proxy authentication, obtain the proxy credentials through your application’s secret provider. Set the parsed proxy URL’s User with url.UserPassword before passing it to http.ProxyURL. The transport uses that user information for proxy authentication. Store endpoint settings and credentials separately, and avoid logging the proxy URL after adding credentials. An application can take a username and password from separate secret values without asking developers to put them on the command line. Proxy authorization in Go’s transport
Distinguish a Go CONNECT error from a website error
Seeing proxy CONNECT returned HTTP 407 means the proxy refused to open the tunnel without acceptable credentials. Check the proxy’s supported authentication method, the credentials your application sends and the provider’s IP allowlist if it uses one. A CONNECT response is available to OnProxyConnectResponse before the transport checks whether the tunnel opened. If that hook returns an error, client.Do fails and the website request has yet to reach the destination. HTTP 407 troubleshooting
The message IP check returned HTTP 403 comes from the response to the request inside the tunnel. Investigate access rules at the destination or its gateway. A timeout alone gives you less information. It can cover any stage reached before the deadline. Compare the direct run with the proxied run and test the same endpoint with curl to narrow down whether the proxy can be reached and whether the destination responds through it. Run a curl proxy check
In a running service, create the transport and client once and reuse them across requests. Use request contexts for per-operation deadlines. Keep separate clients if different jobs need different proxy routes so that configuration stays with the intended client. For TLS errors, check whether failure occurs on the connection to an HTTPS proxy or inside the tunnel on the destination connection. Configure the approved CA certificates and keep certificate verification enabled.