How to Use HTTP, HTTPS and SOCKS5 Proxies in Go

Set http.Transport.Proxy on the client that sends your requests. Use http.ProxyURL for a fixed endpoint, or http.ProxyFromEnvironment when routing comes from deployment settings. Go’s net/http supports authenticated HTTP, HTTPS and SOCKS5 proxy endpoints through the standard library.

The example checks the public exit IP over HTTPS. Run it from the same machine or container as your application, then verify one read-only request to the API you intend to use.

A laptop, a proxy gateway and a destination server connected in sequence.
A Go HTTP client reaches a destination through its configured proxy.

Run a proxy IP check with net/http

Before running the example, get the host, port, and protocol from your BuyProxies connection details.

Save the complete example as proxy-check.go. It uses the Go standard library and prints the exit IP only after a successful response containing a valid IPv4 or IPv6 address. It sets a five-second TCP dial timeout and a fifteen-second request deadline, including the response body. It checks the first response without following redirects and accepts a body of up to 128 bytes.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/netip"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

type proxyConnectError int

func (status proxyConnectError) Error() string {
	return fmt.Sprintf("proxy CONNECT returned HTTP %d", status)
}

func checkIP(target string) error {
	proxy, err := url.Parse(os.Getenv("PROXY_URL"))
	if err != nil || proxy.Hostname() == "" || proxy.User != nil ||
		proxy.Path != "" && proxy.Path != "/" || proxy.RawQuery != "" || proxy.ForceQuery || proxy.Fragment != "" {
		return errors.New("set PROXY_URL to a proxy URL with host and port, without credentials")
	}
	port, err := strconv.ParseUint(proxy.Port(), 10, 16)
	if err != nil || port == 0 {
		return errors.New("set a valid port in PROXY_URL")
	}
	switch proxy.Scheme {
	case "http", "https", "socks5", "socks5h":
	default:
		return errors.New("PROXY_URL must use http, https, socks5 or socks5h")
	}
	user, hasUser := os.LookupEnv("PROXY_USER")
	password, hasPassword := os.LookupEnv("PROXY_PASSWORD")
	if hasUser != hasPassword || hasUser && (user == "" || password == "") {
		return errors.New("set both PROXY_USER and PROXY_PASSWORD, or leave both unset")
	}
	if hasUser {
		proxy.User = url.UserPassword(user, password)
	}

	transport := http.DefaultTransport.(*http.Transport).Clone()
	defer transport.CloseIdleConnections()
	transport.Proxy = http.ProxyURL(proxy)
	transport.DialContext = (&net.Dialer{Timeout: 5 * time.Second}).DialContext
	transport.OnProxyConnectResponse = func(_ context.Context, _ *url.URL, _ *http.Request, response *http.Response) error {
		if response.StatusCode != http.StatusOK {
			return proxyConnectError(response.StatusCode)
		}
		return nil
	}
	client := &http.Client{
		Transport: transport,
		CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
	if err != nil || request.URL.Hostname() == "" || request.URL.User != nil ||
		request.URL.Scheme != "http" && request.URL.Scheme != "https" {
		return errors.New("target must be an HTTP or HTTPS URL without credentials")
	}
	response, err := client.Do(request)
	if err != nil {
		var connectFailure proxyConnectError
		if errors.As(err, &connectFailure) {
			return connectFailure
		}
		if errors.Is(err, context.DeadlineExceeded) {
			return errors.New("proxy check timed out")
		}
		return errors.New("request through proxy failed")
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return fmt.Errorf("endpoint returned HTTP %d", response.StatusCode)
	}

	const maxIPResponse = 128
	body, err := io.ReadAll(io.LimitReader(response.Body, maxIPResponse+1))
	if err != nil {
		return errors.New("could not read the IP response")
	}
	if len(body) > maxIPResponse {
		return errors.New("IP response exceeded 128 bytes")
	}
	ip, err := netip.ParseAddr(strings.TrimSpace(string(body)))
	if err != nil || ip.Zone() != "" {
		return errors.New("endpoint did not return an IP address")
	}
	fmt.Println(ip)
	return nil
}

func main() {
	target := "https://api64.ipify.org"
	switch len(os.Args) {
	case 1:
	case 2:
		target = os.Args[1]
	default:
		fmt.Fprintln(os.Stderr, "usage: go run proxy-check.go [target URL]")
		os.Exit(2)
	}
	if err := checkIP(target); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Run go run proxy-check.go after configuring the proxy below. To use a diagnostic endpoint you control, pass its URL as the single argument. It should return one IP address as plain text.

go run proxy-check.go https://ip-check.example.com/

Connect through an authenticated HTTP proxy

Set PROXY_URL to the endpoint from your provider. An http:// proxy can carry traffic to an https:// destination. For HTTPS, Go sends CONNECT to the proxy and starts TLS with the destination inside the tunnel. The proxy URL describes the first connection. Basic proxy credentials on a plain HTTP connection travel outside that TLS tunnel.

In Bash, replace the sample host and port, then enter your proxy credentials at the prompts. For a deployed service, inject the credentials from a secret store.

(
    export PROXY_URL='http://proxy.example.com:3128'
    read -r -p 'Proxy username: ' PROXY_USER || exit 1
    read -r -s -p 'Proxy password: ' PROXY_PASSWORD || exit 1
    printf '\n'
    export PROXY_USER PROXY_PASSWORD
    go run proxy-check.go
)

url.UserPassword keeps the credentials separate from the endpoint string you configure. The transport uses them for proxy authentication. Add an API token only to requests to that API. For source-IP authorization, leave both credential variables unset and authorize the public IP of the machine that will run the program. Go URL credentials reference · Proxy authentication guide.

Use an HTTPS proxy endpoint in Go

If your provider lists an HTTPS proxy endpoint, use its HTTPS host and port. Replace the export PROXY_URL line above with this example and keep the same credential prompts.

export PROXY_URL='https://proxy.example.com:8443'

Go establishes TLS with the proxy before sending the CONNECT request and proxy credentials. For an HTTPS destination, it then establishes a second TLS connection inside the tunnel. The Go process needs to trust the certificate for each hostname. Use the system trust store or a CA configured for your client and keep certificate verification enabled.

Use SOCKS5 and verify destination DNS

Replace the PROXY_URL line in the Bash block with your SOCKS5 endpoint and run the same program. Use the port assigned to SOCKS5 by your provider.

export PROXY_URL='socks5://proxy.example.com:1080'

In Go’s net/http.Transport, socks5:// and socks5h:// use the same SOCKS5 path. When the destination is a hostname, Go sends that name in the SOCKS request so the proxy can resolve it. The Go process still needs to resolve the proxy’s own hostname if it was configured by name. Check the behavior again if you switch HTTP libraries. Go Transport documentation · SOCKS5 implementation · Rust proxy guide.

A Go client connects to an HTTPS API through either an HTTP CONNECT tunnel or a SOCKS5 proxy.
Go negotiates a tunnel with the HTTP proxy or a connection with the SOCKS5 proxy before starting TLS with the HTTPS API.

Use HTTP_PROXY, HTTPS_PROXY and NO_PROXY

The default Go HTTP transport uses ProxyFromEnvironment. HTTP_PROXY applies to HTTP destinations and HTTPS_PROXY applies to HTTPS destinations. For example, HTTPS_PROXY=http://proxy.example.com:3128 tells Go to use a plain HTTP connection to the proxy for HTTPS requests. NO_PROXY lists destinations that should connect directly. Environment-based selection also skips loopback destinations.

The example sets transport.Proxy = http.ProxyURL(proxy) for a fixed route, which does not consult NO_PROXY. For a client that should use deployment variables, assign http.ProxyFromEnvironment instead. For a direct comparison client, clone the default transport and set its Proxy field to nil. Go environment proxy reference.

Troubleshoot the first request

What you see What to check
HTTP 407 The HTTP proxy requires or rejected authentication. Check the credentials, the endpoint and any source-IP allowlist.
CONNECT rejected The proxy refused to open the HTTPS tunnel before the destination could respond. Check the status printed by the example. For CONNECT 407, verify the proxy login or allowlist.
SOCKS5 negotiation failure Check the expected port, authentication and whether the proxy can resolve and reach the destination hostname.
Timeout or TLS failure Check endpoint reachability and certificate trust on the machine running Go. For an HTTPS proxy, verify the proxy hostname and CA separately from the destination. Keep certificate and hostname checks enabled.
Successful response with the wrong IP Check that the request used your configured client and compare with the provider’s expected egress IP. The address you connect to can differ from the public exit.
403 or 429 from the destination Check the API’s access rules or rate limit. Honor Retry-After if supplied.

Use the proxy tester to check an endpoint independently and the proxy error guide to narrow down the failure. Once the IP check passes, reuse the same http.Client and transport for requests that share a route so they can reuse connections.

Go proxy FAQ

Is GOPROXY the proxy for net/http requests?

GOPROXY selects where the go command fetches modules. Configure the application’s HTTP transport to route its requests. The program here reads PROXY_URL itself. Go module environment variables.

Do I need a package outside the Go standard library for SOCKS5?

The net/http.Transport in this example handles SOCKS5 for HTTP and HTTPS requests. Check the networking API separately if your application uses raw TCP or UDP.

Can one Go process use multiple proxy configurations?

Yes. Build a separate transport and client for each fixed route. Pick the client before sending each request and avoid modifying a transport after it is in use.

If you use BuyProxies, copy the correct protocol, address and port from My Proxies and test one endpoint before using it in your application. Compare dedicated proxy plans for an exclusive IP, or see the developer proxy examples for other clients.

Sources

Example verified on November 22, 2026 with Go 1.27.4 on Windows. The compiled program passed 14 local checks using synthetic credentials. These checks covered HTTP Basic, CONNECT status, rejection of an untrusted TLS certificate, destination hostnames sent through both SOCKS5 schemes, and invalid responses or configuration. The fixtures listened on loopback and did not forward traffic to the internet. The HTTPS proxy case was also checked with Go 1.27.4 for authenticated CONNECT, a 407 response, and rejection of an untrusted proxy certificate. See our editorial policy and testing methodology.

Scroll to Top