Programming languages

How to use a proxy in Go

Go is popular for fast crawlers and monitoring services because goroutines make high concurrency cheap. The standard net/http package supports authenticated HTTP and SOCKS5 proxies directly through the Proxy field of http.Transport, so no extra module is required.

Below you will build a client with a proxy, add targeting safely with url.UserPassword, switch to SOCKS5, and learn how connection reuse affects rotating and sticky IPs.

Updated 23 November 2026

What you need
Hostgate.firstproxy.shop
HTTP / HTTPS port8000
SOCKS5 port9000
Usernameuser-country-nl
PasswordYOUR_TOKEN

net/http supports HTTP on port 8000 and SOCKS5 on port 9000 with a username and password in the proxy URL. Your username and token appear on the Proxy setup page of your dashboard after your first order.

Setup

How do I connect Go to a proxy?

Follow the steps in order. Replace YOUR_TOKEN with the token from your dashboard and change the country, city or session in the username to suit the job.

  1. Create a module

    Go 1.21 or later is assumed. The examples use only the standard library until the Colly step.

    mkdir proxycheck && cd proxycheck
    go mod init proxycheck
  2. Send a request through the proxy

    Parse the proxy URL, credentials included, and set it on the Transport with http.ProxyURL. Go sends the Proxy-Authorization header for both plain HTTP requests and HTTPS tunnels.

    package main
    
    import (
        "fmt"
        "io"
        "net/http"
        "net/url"
        "time"
    )
    
    func main() {
        proxyURL, err := url.Parse("http://user-country-nl:YOUR_TOKEN@gate.firstproxy.shop:8000")
        if err != nil {
            panic(err)
        }
    
        client := &http.Client{
            Timeout:   30 * time.Second,
            Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
        }
    
        resp, err := client.Get("https://ipinfo.io/json")
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
    
        body, _ := io.ReadAll(resp.Body)
        fmt.Println(resp.StatusCode, string(body))
    }
  3. Build the username with url.UserPassword

    Building the URL as a struct avoids escaping mistakes and keeps targeting readable. This version adds a city and a sticky session.

    func proxyFor(country, city, session string, ttl int) *url.URL {
        user := "user-country-" + country
        if city != "" {
            user += "-city-" + city
        }
        if session != "" {
            user += fmt.Sprintf("-session-%s-ttl-%dm", session, ttl)
        }
        return &url.URL{
            Scheme: "http",
            Host:   "gate.firstproxy.shop:8000",
            User:   url.UserPassword(user, "YOUR_TOKEN"),
        }
    }
    
    transport := &http.Transport{Proxy: http.ProxyURL(proxyFor("nl", "rotterdam", "w1", 15))}
  4. Switch to SOCKS5

    net/http accepts a socks5 scheme in the proxy URL and sends the target hostname to the proxy, so DNS is resolved at the exit. Use port 9000.

    proxyURL, _ := url.Parse("socks5://user-country-nl:YOUR_TOKEN@gate.firstproxy.shop:9000")
    client := &http.Client{
        Timeout:   30 * time.Second,
        Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
    }
  5. Control rotation with keep-alive and one client per session

    A Transport keeps connections open and reuses them, and a reused tunnel keeps its exit IP. For a fresh IP on every request with a rotating username, set DisableKeepAlives: true. For sticky work, give each session its own Transport and client and keep keep-alive on for speed.

    // rotating: new connection, new IP per request
    rotating := &http.Client{Transport: &http.Transport{
        Proxy:             http.ProxyURL(proxyFor("nl", "", "", 0)),
        DisableKeepAlives: true,
    }}
    
    // sticky: one client per worker, each with its own session
    for w := 0; w < 4; w++ {
        go func(w int) {
            c := &http.Client{Transport: &http.Transport{
                Proxy: http.ProxyURL(proxyFor("nl", "", fmt.Sprintf("w%d", w), 20)),
            }}
            _ = c // use c for every request of this worker
        }(w)
    }
    _ = rotating
  6. Use the proxy in Colly

    Colly v2 takes the proxy as a string with SetProxy, or a function with SetProxyFunc for per-request choices.

    // go get github.com/gocolly/colly/v2
    c := colly.NewCollector()
    if err := c.SetProxy("http://user-country-nl:YOUR_TOKEN@gate.firstproxy.shop:8000"); err != nil {
        log.Fatal(err)
    }
    c.OnResponse(func(r *colly.Response) { fmt.Println(string(r.Body)) })
    c.Visit("https://ipinfo.io/json")
Test

How do I check that the proxy works?

Run the program from step 2. It prints the status code and the ipinfo.io JSON for the exit IP.

A working proxy returns a response like the one shown, trimmed to the main fields. The IP belongs to the exit, the city and country follow your username, and the time zone is where that IP is located, here Netherlands.

go run .
ipinfo.io/json response
{
  "ip": "203.0.113.24",
  "city": "Amsterdam",
  "country": "NL",
  "timezone": "Europe/Amsterdam"
}

203.0.113.24 is a documentation address. Your result shows a real exit IP.

Targeting

How do I set country, city and session in the username?

All targeting is written into the username, so Go needs no extra settings to change location. Parts are joined with hyphens in this order after your proxy user. The password is always your token.

Proxy username parts
PartFormatExampleRule
Country-country-{cc}-country-nlRequired. Two-letter country code in lowercase. 64 countries are available.
City-city-{city}-city-amsterdamOptional. City name in lowercase, spaces become hyphens. 172 cities are available.
Session-session-{id}-session-a1b2c3Optional. Any letters and digits you choose. The same id keeps the same IP, a new id gets a new IP.
Session length-ttl-{minutes}m-ttl-30mUsed with a session. Residential 1 to 120 minutes, mobile 1 to 60, long-acting ISP up to 720 (12 hours).
Full usernameuser-country-nl-city-amsterdam-session-a1b2c3-ttl-30m

Find country codes and city values on the proxy locations page.

Troubleshooting

Go proxy errors and fixes

The problems people run into most often with Go, with the message you are likely to see and how to solve it.

Get "https://...": Proxy Authentication Required

Go returns the CONNECT status text as an error when the gateway answers 407. Build the URL with url.UserPassword to rule out escaping problems, then check the token in the dashboard.

context deadline exceeded (Client.Timeout exceeded while awaiting headers)

The client timeout fired. Keep Timeout on the client, add TLSHandshakeTimeout and ResponseHeaderTimeout on the Transport, and retry with a new session name.

proxyconnect tcp: dial tcp: lookup ... no such host

The gateway host is misspelled or DNS on the machine is failing. Check the host in the proxy URL and test with curl from the same machine.

A rotating username always shows one IP

Connection reuse keeps the same tunnel. Set DisableKeepAlives: true on that Transport, or close idle connections with CloseIdleConnections() between batches.

Too many open files under load

Always close resp.Body, reuse clients instead of creating one per request, and cap MaxConnsPerHost so goroutines do not open unlimited tunnels.

FAQ

Go proxy questions

Short answers to what people ask most about using a proxy with Go.

How do I set a proxy for http.Client in Go?

Parse http://username:YOUR_TOKEN@gate.firstproxy.shop:8000 with url.Parse and set Transport: &http.Transport{Proxy: http.ProxyURL(u)} on the client. Go adds the proxy authentication header automatically.

Does Go support SOCKS5 proxies without extra packages?

Yes. net/http accepts socks5:// URLs in Transport.Proxy, including a username and password. golang.org/x/net/proxy is only needed for custom dialers.

Why do my Go requests keep the same IP?

The Transport reuses keep-alive connections, and each tunnel stays on its exit IP. Disable keep-alives for per-request rotation, or use a session name when you want the same IP on purpose.

Does Go read HTTP_PROXY from the environment?

The default Transport uses http.ProxyFromEnvironment, which reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY. A custom Transport only does so if you set Proxy: http.ProxyFromEnvironment.

Get your token and run the first Go request

Create an account, top up from $40 with crypto, and copy the gateway, username and token from the dashboard.