Go HTTP Proxy Integration for Rotating Proxies

To use RotatingProxy in Go, configure an `http.Transport` with a `Proxy` function that returns an authenticated proxy URL for the HTTP/HTTPS gateway on port 7070. For SOCKS5 connections to port 7071, import the `golang.org/x/net/proxy` package to create a dialer.

Key points
  • Use http.Transport.Proxy for HTTP/HTTPS on port 7070 with basic auth in the URL.
  • For SOCKS5 on port 7071, use the golang.org/x/net/proxy package.
  • Target countries, US states, cities, and manage sessions via the username string.
  • Handle authentication errors (407), timeouts, and TLS settings for reliable scraping.

Go HTTP Proxy Configuration with http.Transport

The standard method for a Go HTTP proxy is to set the Proxy field on an http.Transport. This transport is then used by an http.Client. The proxy function must return a *url.URL that includes the gateway host, port, and your proxy user credentials with any targeting options. Here is the basic structure:

package main

import (
    "fmt"
    "net/http"
    "net/url"
)

func main() {
    // Build the proxy URL with authentication and options
    proxyURL, _ := url.Parse("http://USERNAME_net.res_cc.us:PASSWORD@gw.rotatingproxy.cc:7070")

    // Create a transport that uses this proxy
    transport := &http.Transport{
        Proxy: http.ProxyURL(proxyURL),
    }

    // Create an HTTP client that uses this transport
    client := &http.Client{
        Transport: transport,
    }

    // Make a request through the proxy
    resp, err := client.Get("https://httpbin.org/ip")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    // ... read response
}

Replace USERNAME_net.res_cc.us with your actual proxy user login and targeting options, and PASSWORD with its password. The Proxy function in the transport handles both HTTP and HTTPS (CONNECT) requests automatically. This configuration works well for web scraping, price monitoring, and rank tracking jobs coded in Go.

Building the Proxy Username with Targeting Options

All proxy configuration, including network choice and geographic targeting, is encoded in the username part of the proxy URL. The basic format is your proxy user's login, an underscore, then a series of key.value options joined by underscores. For example, to use a mobile network in Germany with a sticky session:

login := "zq4k8m2tva_net.mob_cc.de_sid.a7k2m9_ttl.20"
proxyStr := fmt.Sprintf("http://%s:PASSWORD@gw.rotatingproxy.cc:7070", login)

Key options include net.res (residential), net.mob (mobile), net.dc (datacenter), net.isp (ISP), cc.us (country), st.ca (US state, requires cc.us), and city.new-york. For session control, use sid.<id> and ttl.<minutes>. Omit the sid option to get a new IP on every connection. See the username options documentation for the full syntax and city targeting for available locations.

SOCKS5 Proxy Setup in Go on Port 7071

If your tool or library works better with SOCKS5, use port 7071 and the golang.org/x/net/proxy package. First, install it: go get golang.org/x/net/proxy. Then create a SOCKS5 dialer with authentication and use it in a custom transport.

import (
    "golang.org/x/net/proxy"
    "net"
)

func main() {
    // Create the authenticated SOCKS5 dialer
    auth := &proxy.Auth{
        User:     "USERNAME_net.dc_cc.gb",
        Password: "PASSWORD",
    }
    dialer, err := proxy.SOCKS5("tcp", "gw.rotatingproxy.cc:7071", auth, proxy.Direct)
    if err != nil {
        panic(err)
    }

    // Create a transport that uses this dialer
    transport := &http.Transport{
        DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
            return dialer.Dial(network, addr)
        },
    }

    client := &http.Client{Transport: transport}
    // Use client as before
}

Note that the SOCKS5 gateway does not parse the username options; they are passed through for the gateway's internal routing. All targeting and session rules apply identically. To compare protocols, read HTTP vs SOCKS5 proxies.

Verifying the Exit IP and Location

After configuring your client, verify that traffic is exiting through the proxy with the expected IP and location. Make a simple GET request to an IP information service. This also confirms your authentication and basic connectivity.

resp, err := client.Get("https://api.ipify.org?format=json")
// or use https://ipinfo.io/json for more detail
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Exit IP: %s\n", body)

If you requested a specific country, state, or city, the returned IP should correspond to that location. Geolocation is not perfect; for more on accuracy, read how accurate is IP geolocation. This check is a crucial first step in testing a proxy connection.

Handling Common Proxy Errors in Go

Proper error handling makes your scraper solid. The error seen most often is 407 Proxy Authentication Required. This usually means the username or password in your proxy URL is incorrect, or the proxy user does not have permission for the chosen network. Double-check the credentials and the proxy user's allowed networks in your dashboard. For a detailed guide, see proxy error 407.

Connection timeouts can occur if the target server is slow or if your client does not set appropriate deadlines. Always use a timeout on your http.Client and consider using a context.WithTimeout for individual requests.

client := &http.Client{
    Transport: transport,
    Timeout: 30 * time.Second, // Total request timeout
}

TLS errors sometimes appear if the client's TLS configuration is too strict. You can customize the TLSClientConfig in the transport, but for most public websites, the default is sufficient. Ensure you are using the correct port: 7070 for HTTP/HTTPS, not 7071 (SOCKS5).

Managing Sticky Sessions and IP Rotation

To maintain the same IP across multiple requests (a sticky session), include a sid. (session ID) and optionally a ttl. (time-to-live in minutes) in the username. The IP will be held for the TTL duration as long as the session is active. Reusing the exact same username string (including the same SID) within the TTL window will return you to the same IP. This is essential for tasks like social media management or maintaining a logged-in state.

// Sticky session for 10 minutes (default TTL when sid is set)
sessionUsername := "myuser_net.res_cc.us_st.ca_city.los-angeles_sid.abc123"
// For a new IP on every connection, omit the sid entirely
rotatingUsername := "myuser_net.mob_cc.jp"

If your session IP changes before the TTL expires, it could be because the exit device went offline. The system will automatically move you to a new IP in the same targeted location.

Tips for Running Go Proxy Clients at Scale

When making many concurrent requests, tune the http.Transport settings. Increase MaxIdleConns and MaxIdleConnsPerHost to allow connection reuse, which reduces latency. Be mindful of the account-wide concurrency limit of 1,000 connections.

transport := &http.Transport{
    Proxy:               http.ProxyURL(proxyURL),
    MaxIdleConns:        100,
    MaxIdleConnsPerHost: 10,
    IdleConnTimeout:     90 * time.Second,
}

Use a retry system with exponential backoff for temporary errors like 502s or timeouts. Distribute requests across different proxy users or session IDs if you are hitting rate limits on target sites. For large-scale projects like AI training data collection, monitor your traffic usage via the API to avoid balance depletion. Our planning concurrency for crawlers guide has further advice.

Using the REST API for Account Management

Automate your proxy management by using the RotatingProxy REST API. With an API key from your dashboard, you can check balance, create proxy users, and fetch usage data programmatically. This is useful for dynamically allocating resources in a distributed scraper.

import "net/http"

apiKey := "your_bearer_key_here"
req, _ := http.NewRequest("GET", "https://rotatingproxy.cc/api/v1/balance", nil)
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
resp, err := client.Do(req)

You can use it to enforce monthly GB caps on proxy users or to top up your balance before it runs out.

Reducing Proxy Traffic and Costs in Go

Since billing is pay-as-you-go per GB, efficient traffic use lowers costs. Enable HTTP compression by setting the Accept-Encoding header. Cache responses locally when possible, especially for static resources. Send a HEAD request first to see if a file has changed, avoiding a full download. When scraping, target JSON APIs instead of HTML when available, as outlined in use public APIs before scraping HTML.

Set the DisableCompression field in http.Transport to false (it's false by default) to allow gzip. Monitor your usage patterns in the dashboard to understand where traffic goes. The how to estimate proxy bandwidth guide can help with planning.

Example: Complete Scraper with Rotation and Error Handling

Here is a consolidated example that demonstrates a solid Go scraper using rotating residential proxies with error handling and IP verification.

package main

import (
    "context"
    "fmt"
    "io"
    "log"
    "net/http"
    "net/url"
    "time"
)

func main() {
    // 1. Configure proxy
    proxyURL, _ := url.Parse("http://USERNAME_net.res_cc.us:PASSWORD@gw.rotatingproxy.cc:7070")

    transport := &http.Transport{
        Proxy:               http.ProxyURL(proxyURL),
        MaxIdleConns:        50,
        MaxIdleConnsPerHost: 10,
    }

    client := &http.Client{
        Transport: transport,
        Timeout:   45 * time.Second,
    }

    // 2. Verify exit IP
    verifyIP(client)

    // 3. Make a request to a target
    targetURL := "https://example.com/data"
    req, _ := http.NewRequestWithContext(context.Background(), "GET", targetURL, nil)
    req.Header.Set("User-Agent", "MyScraper/1.0")

    resp, err := client.Do(req)
    if err != nil {
        log.Printf("Request failed: %v", err)
        // Implement retry logic here
        return
    }
    defer resp.Body.Close()

    if resp.StatusCode != 200 {
        log.Printf("Non-200 status: %d", resp.StatusCode)
        // Check for 403, which may indicate a block; consider rotating the session ID
    }

    body, _ := io.ReadAll(resp.Body)
    fmt.Printf("Fetched %d bytes\n", len(body))
}

func verifyIP(c *http.Client) {
    resp, err := c.Get("https://api.ipify.org")
    if err != nil {
        log.Fatal("Proxy connection failed:", err)
    }
    defer resp.Body.Close()
    ip, _ := io.ReadAll(resp.Body)
    log.Println("Connected via IP:", string(ip))
}

This pattern can be adapted for many use cases, from market research to news monitoring.

Questions

Can I use the same Go code for mobile and datacenter proxies?

Yes, the code is identical. You only change the username option from `net.res` to `net.mob` or `net.dc`. The gateway handles the different networks. Choose based on your target's blocking behavior; for example, mobile IPs are often trusted for TikTok proxies.

How do I target a specific city like London or New York?

Add the `city` option to the username, using the lowercase city token with spaces replaced by hyphens. Examples are `city.london` and `city.new-york`. Check the city list in your dashboard or the city targeting help page for available tokens.

My Go program is getting frequent timeouts through the proxy. What should I check?

First, verify your base connectivity without the proxy. Then, ensure you are not exceeding your account's concurrency limit. Increase your client's `Timeout` and consider adjusting transport settings like `ResponseHeaderTimeout`. Test with a simple IP check to see if the issue is with the proxy or the target site. Review proxy timeouts and slow responses.

Does the Go http.Transport handle HTTPS (CONNECT) correctly?

Yes, the standard `http.Transport` with a `Proxy` URL automatically uses the HTTP CONNECT method for HTTPS targets. You do not need any special configuration. The proxy authenticates during the initial CONNECT negotiation.

What's the best way to spread requests among several proxy users in Go?

Create multiple `http.Client` instances, each with its own transport configured with a different proxy URL (different usernames/passwords). Then use a round-robin or random selection method to assign requests to clients. This can help distribute load and avoid per-user traffic caps.

I need to scrape a site that requires JavaScript rendering. Is it possible to use these proxies with a headless browser in Go?

Directly, Go's HTTP client cannot render JavaScript. You would need to drive an external browser like Chrome via an API. However, you can route that browser's traffic through the proxy by configuring the browser's proxy settings to use the RotatingProxy gateway. See our Chrome proxy settings guide for how to do that.

Start with one top-up, use any network

Create an account in a minute, add $40 or more, and the same balance pays for residential, mobile, datacenter and ISP traffic.