Why Use Proxies in Go?
Go has become the language of choice for high-performance networking tools, web scrapers, and API clients. Its lightweight goroutines, built-in concurrency primitives, and a battle-tested net/http standard library make it ideal for proxy-powered applications that need to handle thousands of concurrent requests.
Whether you are building a web scraping pipeline, monitoring SERP rankings, or collecting competitive pricing data, routing your Go HTTP clients through proxies lets you rotate IP addresses, bypass geo-restrictions, and avoid rate limits at scale.
In this guide, you will route Go traffic through ProxyHat with nothing but the standard library, and use the ProxyHat Go SDK for the account side: looking up location codes and checking sub-user traffic. Every code snippet is copy-paste-ready and was run against the live gateway.
Installation
Standard library only
Sending requests through the proxy needs nothing beyond Go's net/http and net/url packages. No extra installation required.
ProxyHat Go SDK
The SDK is a client for the ProxyHat account API: sub-users, location codes, usage analytics. It does not send your HTTP requests itself; your traffic always goes through net/http as shown below.
go get github.com/ProxyHatCom/go-sdk
Authentication and Basic Setup
ProxyHat uses username-password authentication over the proxy endpoint. You will find your sub-user's proxy credentials in the ProxyHat dashboard (see the documentation for details). A typical proxy URL looks like this:
http://USERNAME:PASSWORD@gate.proxyhat.com:8080
Keep credentials out of source code. Use environment variables or a .env file:
export PROXYHAT_USER="your_username"
export PROXYHAT_PASS="your_password"
Simple GET Request with a Proxy
Here is the minimal approach using only the standard library:
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
)
func main() {
proxyURL, err := url.Parse(fmt.Sprintf(
"http://%s:%s@gate.proxyhat.com:8080",
os.Getenv("PROXYHAT_USER"),
os.Getenv("PROXYHAT_PASS"),
))
if err != nil {
log.Fatal(err)
}
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
resp, err := client.Get("https://httpbin.org/ip")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Run it and you will see a residential IP address instead of your own. Every request is routed through ProxyHat's residential proxy pool.
Using Different Proxy Types
ProxyHat supports two rotating proxy types (datacenter is coming soon), each suited to different workloads. You select the type with a username flag on the same port (residential is the default):
| Type | Username flag | Best For | Avg Latency |
|---|---|---|---|
| Residential | none (default) | Web scraping, ad verification | ~800 ms |
| Datacenter | coming soon | High-speed bulk requests | ~200 ms |
| Mobile | -type-mobile | Social media, app testing | ~1200 ms |
For a deeper comparison of when to use each type, see our guide on residential vs datacenter vs mobile proxies.
// Same host and port for every type: the username selects it
user, pass := os.Getenv("PROXYHAT_USER"), os.Getenv("PROXYHAT_PASS")
residential := fmt.Sprintf("http://%s:%s@gate.proxyhat.com:8080", user, pass)
mobile := fmt.Sprintf("http://%s-type-mobile:%s@gate.proxyhat.com:8080", user, pass)
// datacenter: coming soon at ProxyHat
Configuring http.Transport for Proxies
For full control, configure the http.Transport directly. This lets you tune connection pooling, TLS settings, and timeouts:
package main
import (
"crypto/tls"
"net/http"
"net/url"
"time"
)
func newProxyClient(proxyAddr string) (*http.Client, error) {
proxyURL, err := url.Parse(proxyAddr)
if err != nil {
return nil, err
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
}
client := &http.Client{
Transport: transport,
Timeout: 30 * time.Second,
}
return client, nil
}
Looking Up Locations and Usage with the ProxyHat Go SDK
The ProxyHat Go SDK talks to the account API with your API key. Two things it is handy for in a scraper: finding the exact region and city codes for geo-targeting, and checking how much traffic each sub-user has used.
package main
import (
"context"
"fmt"
"log"
"os"
proxyhat "github.com/ProxyHatCom/go-sdk"
)
func main() {
client := proxyhat.NewClient(os.Getenv("PROXYHAT_API_KEY"))
ctx := context.Background()
// City codes for geo-targeting. A city always needs its region.
country, region := "us", "new_york"
cities, err := client.Locations.Cities(ctx, &proxyhat.CityParams{
RegionParams: proxyhat.RegionParams{CountryCode: &country},
RegionCode: ®ion,
})
if err != nil {
log.Fatal(err)
}
for _, c := range cities {
fmt.Printf("%-20s -country-%s-region-%s-city-%s\n", c.Name, country, region, c.Code)
}
// Traffic used by each sub-user
users, err := client.SubUsers.List(ctx)
if err != nil {
log.Fatal(err)
}
for _, u := range users {
fmt.Println(u.ProxyUsername, u.LifecycleStatus, "used:", u.UsedTraffic)
}
}
The SDK returns typed structs and API errors. Check the API documentation for the full method reference.
Rotating vs Sticky Sessions
ProxyHat supports two session modes:
- Rotating (default) — every new connection gets a new IP. Ideal for large-scale web scraping.
- Sticky — the same IP is held for the duration you set in the username (from one minute up to 24 hours). Useful for multi-step flows like login sequences or paginated crawls.
Rotating sessions
Go reuses connections by default, and a reused tunnel keeps the same exit IP. To get a new IP on every request, switch keep-alive off:
proxyURL := &url.URL{
Scheme: "http",
User: url.UserPassword(os.Getenv("PROXYHAT_USER"), os.Getenv("PROXYHAT_PASS")),
Host: "gate.proxyhat.com:8080",
}
// No session flags = rotating. Turn keep-alive off so each request opens
// a new tunnel through the gateway and gets a new exit IP.
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
DisableKeepAlives: true,
},
Timeout: 30 * time.Second,
}
for i := 0; i < 5; i++ {
resp, err := client.Get("https://api.ipify.org")
if err != nil {
log.Println(err)
continue
}
ip, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("Request %d: %s\n", i+1, ip)
}
Sticky sessions
Add a session ID (8–32 hex characters) and a lifetime to the username. All requests with the same ID exit from the same IP until the lifetime runs out:
// Sticky: -sid-<hex id>-ttl-<duration> keeps one exit IP for the session
sid := make([]byte, 8)
if _, err := rand.Read(sid); err != nil { // crypto/rand
log.Fatal(err)
}
username := fmt.Sprintf("%s-country-us-sid-%x-ttl-10m", os.Getenv("PROXYHAT_USER"), sid)
proxyURL := &url.URL{
Scheme: "http",
User: url.UserPassword(username, os.Getenv("PROXYHAT_PASS")),
Host: "gate.proxyhat.com:8080",
}
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
Timeout: 30 * time.Second,
}
// Every request through this client exits from the same IP for 10 minutes
resp1, err := client.Get("https://example.com/login")
// ...
resp2, err := client.Get("https://example.com/account")
One session per worker
If you run sticky sessions in parallel, give each goroutine its own session ID instead of sharing one:
// One session ID per worker: a single sticky session is not meant
// to carry dozens of parallel connections
func newSessionID() string {
b := make([]byte, 8)
rand.Read(b)
return hex.EncodeToString(b)
}
Geo-Targeted Requests
Need IPs from a specific country? ProxyHat supports 190+ locations. Add the location to the username; region and city codes come from the locations API (see the SDK example above):
user := os.Getenv("PROXYHAT_USER")
// Country only (ISO 3166-1 alpha-2, lower case)
us := user + "-country-us"
// Region + city: the city code always follows its region code
nyc := user + "-country-us-region-new_york-city-new_york_city"
// Mobile exit in Germany
deMobile := user + "-country-de-type-mobile"
// Build the proxy URL from any of them
proxyURL := &url.URL{
Scheme: "http",
User: url.UserPassword(nyc, os.Getenv("PROXYHAT_PASS")),
Host: "gate.proxyhat.com:8080",
}
Geo-targeting is essential for localized SERP tracking, regional pricing checks, and content availability testing.
Error Handling and Retries
Network requests through proxies can fail for transient reasons: connection resets, timeouts, or temporary blocks. Robust error handling is critical for production scrapers.
Which errors to retry
// retryable reports whether a failed request is worth repeating.
// "Proxy Authentication Required" (407) means wrong credentials or an
// unknown username flag: retrying the same request will not fix it.
func retryable(resp *http.Response, err error) bool {
if err != nil {
return !strings.Contains(err.Error(), "Proxy Authentication Required")
}
return resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500
}
Manual retry with exponential backoff
package main
import (
"fmt"
"math"
"net/http"
"time"
)
func fetchWithRetry(client *http.Client, url string, maxRetries int) (*http.Response, error) {
var lastErr error
for attempt := 0; attempt <= maxRetries; attempt++ {
resp, err := client.Get(url)
if err == nil && resp.StatusCode < 500 {
return resp, nil
}
if err != nil {
lastErr = err
} else {
lastErr = fmt.Errorf("HTTP %d", resp.StatusCode)
resp.Body.Close()
}
backoff := time.Duration(math.Pow(2, float64(attempt))) * time.Second
time.Sleep(backoff)
}
return nil, fmt.Errorf("all %d retries failed: %w", maxRetries, lastErr)
}
Concurrent Scraping with Goroutines
Go's concurrency model is its superpower. With goroutines and channels, you can scrape hundreds of URLs concurrently while keeping memory usage minimal.
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"sync"
"time"
)
type Result struct {
URL string
StatusCode int
Body string
Err error
}
func scrape(client *http.Client, urls []string, concurrency int) []Result {
results := make([]Result, len(urls))
sem := make(chan struct{}, concurrency) // semaphore
var wg sync.WaitGroup
for i, u := range urls {
wg.Add(1)
go func(idx int, target string) {
defer wg.Done()
sem <- struct{}{} // acquire
defer func() { <-sem }() // release
resp, err := client.Get(target)
if err != nil {
results[idx] = Result{URL: target, Err: err}
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
results[idx] = Result{
URL: target,
StatusCode: resp.StatusCode,
Body: string(body),
Err: err,
}
}(i, u)
}
wg.Wait()
return results
}
func main() {
proxyURL := &url.URL{
Scheme: "http",
User: url.UserPassword(os.Getenv("PROXYHAT_USER"), os.Getenv("PROXYHAT_PASS")),
Host: "gate.proxyhat.com:8080",
}
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxIdleConnsPerHost: 20,
},
Timeout: 30 * time.Second,
}
urls := []string{
"https://example.com/page/1",
"https://example.com/page/2",
"https://example.com/page/3",
// ... hundreds more
}
results := scrape(client, urls, 20)
for _, r := range results {
if r.Err != nil {
fmt.Printf("FAIL %s: %v\n", r.URL, r.Err)
} else {
fmt.Printf("OK %s: %d bytes\n", r.URL, len(r.Body))
}
}
}
Rate Limiting with a Semaphore
The scraper above already uses a semaphore channel to cap concurrency. For finer-grained rate limiting (e.g., N requests per second), use golang.org/x/time/rate:
package main
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"golang.org/x/time/rate"
)
func main() {
proxyURL := &url.URL{
Scheme: "http",
User: url.UserPassword(os.Getenv("PROXYHAT_USER"), os.Getenv("PROXYHAT_PASS")),
Host: "gate.proxyhat.com:8080",
}
client := &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
Timeout: 30 * time.Second,
}
// Allow 10 requests per second, burst of 20
limiter := rate.NewLimiter(10, 20)
urls := []string{"https://example.com/1", "https://example.com/2"}
for _, u := range urls {
if err := limiter.Wait(context.Background()); err != nil {
log.Fatal(err)
}
resp, err := client.Get(u)
if err != nil {
fmt.Printf("Error: %v\n", err)
continue
}
resp.Body.Close()
fmt.Printf("%s - %d\n", u, resp.StatusCode)
}
}
Production Tips
Connection pooling
Go's http.Transport maintains a pool of idle connections by default. For proxy workloads, tune these settings:
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxIdleConns: 200,
MaxIdleConnsPerHost: 50,
MaxConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
}
Timeouts
Always set timeouts. A scraper without timeouts will eventually hang on a stalled connection:
client := &http.Client{
Transport: transport,
Timeout: 30 * time.Second, // total request timeout
}
// Or use context for per-request control
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", targetURL, nil)
resp, err := client.Do(req)
Graceful shutdown
In long-running scrapers, listen for OS signals to shut down cleanly:
package main
import (
"context"
"os"
"os/signal"
"syscall"
)
func main() {
ctx, stop := signal.NotifyContext(
context.Background(),
os.Interrupt, syscall.SIGTERM,
)
defer stop()
// Pass ctx to your scraping functions
// When Ctrl+C is pressed, ctx is cancelled
// and in-flight requests wind down gracefully
runScraper(ctx)
}
Logging and observability
Wrap your HTTP transport to log request timing and status codes. This helps identify slow targets and proxy errors in production:
type loggingTransport struct {
inner http.RoundTripper
}
func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
start := time.Now()
resp, err := t.inner.RoundTrip(req)
elapsed := time.Since(start)
if err != nil {
log.Printf("ERR %s %s (%v) err=%v", req.Method, req.URL, elapsed, err)
} else {
log.Printf("OK %s %s (%v) status=%d", req.Method, req.URL, elapsed, resp.StatusCode)
}
return resp, err
}
Key Takeaways
- Go's goroutines + proxies = massive concurrency. You can run thousands of proxy-routed requests with minimal memory overhead.
- The standard library is all you need to send traffic through ProxyHat: set
Proxyonhttp.Transportand put targeting flags in the username. The ProxyHat Go SDK covers the account API (locations, sub-users, usage).- Use rotating IPs for scraping at scale (with keep-alive off for a new IP per request) and sticky sessions for multi-step workflows like login flows.
- Always set timeouts on both the
http.Clientand viacontext.WithTimeoutfor per-request control.- Rate-limit responsibly with
golang.org/x/time/rateand cap concurrency with semaphore channels.- Geo-target your requests with country, region and city codes in the username to access 190+ locations worldwide.
- Check our guide on the best proxies for web scraping to choose the right plan for your workload.






