Perché usare i proxy in Go?
Go è diventato il linguaggio di riferimento per strumenti di networking ad alte prestazioni, web scraper e client API. Le sue goroutine leggere, le primitive di concorrenza integrate e una libreria standard net/http collaudata lo rendono ideale per applicazioni basate su proxy che devono gestire migliaia di richieste concorrenti.
Che tu stia costruendo una pipeline di web scraping, monitorando i ranking SERP o raccogliendo dati sui prezzi della concorrenza, instradare i tuoi client HTTP Go attraverso i proxy ti permette di ruotare gli indirizzi IP, aggirare le restrizioni geografiche ed evitare i rate limit su larga scala.
In questa guida instraderai il traffico Go attraverso ProxyHat usando solo la libreria standard e utilizzerai il ProxyHat Go SDK per la parte relativa all'account: cercare i codici di località e controllare il traffico dei sub-utenti. Ogni frammento di codice è pronto da copiare e incollare ed è stato eseguito sul gateway live.
Installazione
Solo libreria standard
Inviare richieste attraverso il proxy non richiede nulla oltre ai pacchetti net/http e net/url di Go. Nessuna installazione aggiuntiva necessaria.
ProxyHat Go SDK
L'SDK è un client per l'API dell'account ProxyHat: sub-utenti, codici di località, analytics di utilizzo. Non invia le tue richieste HTTP direttamente; il tuo traffico passa sempre attraverso net/http come mostrato di seguito.
go get github.com/ProxyHatCom/go-sdk
Autenticazione e configurazione di base
ProxyHat utilizza l'autenticazione username-password sull'endpoint proxy. Troverai le credenziali proxy del tuo sub-utente nella dashboard di ProxyHat (vedi la documentazione per i dettagli). Un URL proxy tipico è simile a questo:
http://USERNAME:PASSWORD@gate.proxyhat.com:8080
Tieni le credenziali fuori dal codice sorgente. Usa variabili d'ambiente o un file .env:
export PROXYHAT_USER="your_username"
export PROXYHAT_PASS="your_password"
Richiesta GET semplice con un proxy
Ecco l'approccio minimo usando solo la libreria standard:
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))
}
Eseguilo e vedrai un indirizzo IP residenziale al posto del tuo. Ogni richiesta viene instradata attraverso il pool di proxy residenziali di ProxyHat.
Usare diversi tipi di proxy
ProxyHat supporta due tipi di proxy rotanti (datacenter in arrivo), ciascuno adatto a carichi di lavoro diversi. Selezioni il tipo con un flag nel username sulla stessa porta (il residenziale è il default):
| Tipo | Flag nel username | Ideale per | Latenza media |
|---|---|---|---|
| Residenziale | nessuno (default) | Web scraping, verifica annunci | ~800 ms |
| Datacenter | in arrivo | Richieste in blocco ad alta velocità | ~200 ms |
| Mobile | -type-mobile | Social media, test di app | ~1200 ms |
Per un confronto più approfondito su quando usare ciascun tipo, consulta la nostra guida su proxy residenziali vs datacenter vs mobile.
// 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
Configurare http.Transport per i proxy
Per il controllo completo, configura direttamente http.Transport. Questo ti permette di ottimizzare il connection pooling, le impostazioni TLS e i timeout:
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
}
Cercare località e utilizzo con il ProxyHat Go SDK
Il ProxyHat Go SDK comunica con l'API dell'account usando la tua API key. Due cose utili in uno scraper: trovare i codici esatti di regione e città per il geo-targeting e controllare quanto traffico ha usato ciascun sub-utente.
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)
}
}
L'SDK restituisce struct tipizzate ed errori API. Consulta la documentazione API per il riferimento completo dei metodi.
Sessioni rotanti vs sticky
ProxyHat supporta due modalità di sessione:
- Rotante (default) — ogni nuova connessione ottiene un nuovo IP. Ideale per web scraping su larga scala.
- Sticky — lo stesso IP viene mantenuto per la durata che imposti nel username (da un minuto fino a 24 ore). Utile per flussi a più passaggi come sequenze di login o crawl paginati.
Sessioni rotanti
Go riutilizza le connessioni per default, e un tunnel riutilizzato mantiene lo stesso IP di uscita. Per ottenere un nuovo IP a ogni richiesta, disattiva il keep-alive:
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)
}
Sessioni sticky
Aggiungi un ID di sessione (8–32 caratteri esadecimali) e una durata al username. Tutte le richieste con lo stesso ID escono dallo stesso IP finché la durata non scade:
// 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")
Una sessione per worker
Se esegui sessioni sticky in parallelo, assegna a ogni goroutine il proprio ID di sessione invece di condividerne uno:
// 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)
}
Richieste geo-targetizzate
Ti servono IP da un paese specifico? ProxyHat supporta oltre 190 località. Aggiungi la località al username; i codici di regione e città provengono dall'API delle località (vedi l'esempio SDK sopra):
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",
}
Il geo-targeting è essenziale per il SERP tracking localizzato, i controlli sui prezzi regionali e i test di disponibilità dei contenuti.
Gestione degli errori e retry
Le richieste di rete attraverso i proxy possono fallire per motivi transitori: reset delle connessioni, timeout o blocchi temporanei. Una gestione robusta degli errori è fondamentale per gli scraper in produzione.
Quali errori ritentare
// 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
}
Retry manuale con backoff esponenziale
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)
}
Scraping concorrente con le goroutine
Il modello di concorrenza di Go è il suo superpotere. Con goroutine e channel, puoi fare scraping di centinaia di URL in modo concorrente mantenendo l'uso di memoria minimo.
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 con un semaforo
Lo scraper sopra usa già un canale semaforo per limitare la concorrenza. Per un rate limiting più granulare (ad es., N richieste al secondo), usa 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)
}
}
Consigli per la produzione
Connection pooling
Il http.Transport di Go mantiene per default un pool di connessioni inattive. Per carichi di lavoro con proxy, ottimizza queste impostazioni:
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxIdleConns: 200,
MaxIdleConnsPerHost: 50,
MaxConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
}
Timeout
Imposta sempre i timeout. Uno scraper senza timeout prima o poi si bloccherà su una connessione in stallo:
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)
Spegnimento controllato
Negli scraper di lunga durata, ascolta i segnali del sistema operativo per chiudere in modo pulito:
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 e osservabilità
Avvolgi il tuo transport HTTP per registrare i tempi delle richieste e i codici di stato. Questo aiuta a individuare target lenti ed errori proxy in produzione:
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
}
Punti chiave
- Goroutine di Go + proxy = concorrenza massiccia. Puoi eseguire migliaia di richieste instradate tramite proxy con un overhead di memoria minimo.
- La libreria standard è tutto ciò che ti serve per inviare traffico attraverso ProxyHat: imposta
Proxysuhttp.Transporte metti i flag di targeting nel username. Il ProxyHat Go SDK copre l'API dell'account (località, sub-utenti, utilizzo).- Usa IP rotanti per lo scraping su larga scala (con keep-alive disattivato per un nuovo IP a ogni richiesta) e sessioni sticky per flussi a più passaggi come i flussi di login.
- Imposta sempre i timeout sia sul
http.Clientsia tramitecontext.WithTimeoutper il controllo per singola richiesta.- Applica il rate limiting in modo responsabile con
golang.org/x/time/ratee limita la concorrenza con canali semaforo.- Fai geo-targeting delle richieste con codici di paese, regione e città nel username per accedere a oltre 190 località in tutto il mondo.
- Consulta la nostra guida sui migliori proxy per il web scraping per scegliere il piano giusto per il tuo carico di lavoro.






