Colly Proxy Setup for Rotating IPs

This guide explains how to integrate RotatingProxy with the Colly web scraping framework in Go. You will configure Colly to route requests through our gateway for IP rotation and geo-targeting.

Key points
  • Use the `SetProxyFunc` method to inject a dynamic proxy for each request.
  • Build the full proxy URL with authentication and targeting options in the username.
  • SOCKS5 support on port 7071 works with Colly's HTTP transport.
  • Manage sticky sessions with a session ID to keep the same IP across requests.

Colly Proxy Integration Overview

Integrating a Colly proxy involves setting a custom HTTP transport that routes requests through the RotatingProxy gateway. Colly's collector uses the standard Go `net/http` client, allowing you to configure a proxy function or a custom transport. The core steps are building the correct proxy URL with your authentication and targeting options, then applying it to the collector. This setup enables you to use rotating IPs from our residential, mobile, datacenter, or ISP networks for tasks like web scraping and price monitoring.

Where Proxy Settings Go in Colly

Proxy configuration in Colly is applied at the collector level, typically before you start making requests. The primary method is `collector.SetProxyFunc`, which accepts a function that returns a proxy URL string for each request. This is ideal for rotating proxies because you can generate a new proxy string on the fly. Alternatively, you can set a fixed proxy by creating a custom `http.Transport` with a `Proxy` function and assigning it to the collector's `Transport` field. The choice depends on whether you need per-request rotation or a static proxy setup for a session.

HTTP Proxy Setup on Port 7070

To use the HTTP(S) proxy on port 7070, construct a proxy URL in the format `http://USERNAME:PASSWORD@gw.rotatingproxy.cc:7070`. The username must include your proxy user login and any targeting options. Here is a basic Colly setup with a fixed proxy string for all requests:

package main

import (
    "github.com/gocolly/colly"
    "net/http"
    "net/url"
)

func main() {
    c := colly.NewCollector()

    proxyURL, _ := url.Parse("http://USERNAME_net.res_cc.us:PASSWORD@gw.rotatingproxy.cc:7070")
    c.WithTransport(&http.Transport{
        Proxy: http.ProxyURL(proxyURL),
    })

    c.OnResponse(func(r *colly.Response) {
        println("Request succeeded")
    })

    c.Visit("https://httpbin.org/ip")
}

This configures all requests from this collector to exit through US residential IPs. For dynamic rotation without a session ID, you would use `SetProxyFunc` to generate a new URL for each request, omitting the `sid` option. This approach is common for rank tracking where each request should originate from a different IP.

SOCKS5 Proxy Setup on Port 7071

Colly supports SOCKS5 proxies through a custom transport using the `golang.org/x/net/proxy` package. First, make sure you have the package: `go get golang.org/x/net/proxy`. Then, configure the collector to use the SOCKS5 gateway on port 7071. The authentication is still passed in the URL.

import (
    "github.com/gocolly/colly"
    "golang.org/x/net/proxy"
    "net"
    "net/http"
    "net/url"
)

func main() {
    c := colly.NewCollector()

    auth := proxy.Auth{
        User:     "USERNAME_net.mob_cc.de",
        Password: "PASSWORD",
    }
    dialer, err := proxy.SOCKS5("tcp", "gw.rotatingproxy.cc:7071", &auth, proxy.Direct)
    if err != nil {
        panic(err)
    }

    c.WithTransport(&http.Transport{
        Dial: dialer.Dial,
    })

    c.Visit("https://api.ipify.org")
}

SOCKS5 can be beneficial for certain types of traffic, as it handles both HTTP and raw TCP at the proxy level. For a comparison, see our guide on HTTP port vs SOCKS5 port.

Passing Targeting and Session Options

All targeting and session control is done through the username field. You append options to your proxy user login with underscores. For example, to target Chicago residential IPs with a 30-minute sticky session, build the username like this: USERNAME_net.res_cc.us_st.il_city.chicago_sid.abc123_ttl.30. In Colly, you can generate these usernames dynamically in your `SetProxyFunc`. Here's a pattern for rotating across multiple cities:

cities := []string{"city.new-york", "city.los-angeles", "city.chicago"}
cityIndex := 0

c.SetProxyFunc(func(r *http.Request) (*url.URL, error) {
    username := fmt.Sprintf("USERNAME_net.res_cc.us_%s", cities[cityIndex])
    cityIndex = (cityIndex + 1) % len(cities)
    proxyStr := fmt.Sprintf("http://%s:PASSWORD@gw.rotatingproxy.cc:7070", username)
    return url.Parse(proxyStr)
})

For session persistence, keep the same `sid` value across requests within the TTL. This is essential for tasks like social media management where you need a consistent IP.

Verifying the Exit IP and Location

After setup, verify that your requests are using the proxy and showing the expected IP and location. A simple test is to scrape a service that returns your IP. Colly can parse the response to confirm.

c.OnResponse(func(r *colly.Response) {
    fmt.Printf("Exit IP: %s\n", string(r.Body))
})

c.Visit("https://api.ipify.org")

For more detailed geolocation, use a service like `https://ipinfo.io/json` and parse the JSON response. This verifies your targeting by country, state, or city is functioning. If the IP doesn't match, double-check the username options. Our IP check tools guide lists more services.

Common Errors and Fixes

407 Proxy Authentication Required: This means the proxy rejected your credentials. Check that the username and password are correct and that the proxy user is active and allowed to use the chosen network (e.g., `net.mob`). Ensure the username options are formatted correctly with underscores. See our dedicated error 407 page.

Timeouts: Timeouts can occur if the target site is slow or if your connection to the gateway is unstable. Increase Colly's default timeout by setting a custom `http.Client` on the collector. Also, implement a retry mechanism using Colly's `OnError` callback.

c.SetClient(&http.Client{
    Timeout: 60 * time.Second,
})

c.OnError(func(r *colly.Response, err error) {
    if strings.Contains(err.Error(), "timeout") {
        // Implement retry logic
    }
})

TLS/SSL Errors: When using the HTTP proxy port 7070 for HTTPS sites, Colly's transport handles CONNECT tunneling automatically. If you encounter TLS handshake failures, ensure you are not using a custom TLS configuration that interferes. For SOCKS5, TLS is handled directly between your client and the target.

Tips for Running at Scale

When scaling your Colly crawler with rotating proxies, manage concurrency and sessions carefully. Each account can have up to 1,000 concurrent connections across all proxy users. Distribute traffic among multiple proxy users to stay under individual concurrency limits and to isolate different parts of your crawler. Use the `SetProxyFunc` to load balance across a list of proxy user credentials. Implement polite crawling with delays and respect `robots.txt` (Colly has built-in support). For large-scale projects like ecommerce data collection, estimate your bandwidth needs with our bandwidth estimation guide to understand costs.

Using Multiple Proxy Networks

Your balance covers all four networks, so you can switch between them based on need. For example, use residential proxies for Google search, mobile proxies for TikTok, and datacenter proxies for high-speed financial data collection. In Colly, you can design your proxy function to select a network based on the target domain or task. This helps in avoiding IP bans by matching the IP type to the site's expectations.

Integrating with Other Go HTTP Clients

Colly is built on `net/http`, so the proxy configuration principles apply to any Go HTTP client. If you use a different client like `resty` or the standard `http.Client`, you can apply the same transport setup. For more generic Go examples, see our Go HTTP proxy integration guide. The username grammar and gateway details remain identical.

Monitoring Usage and Managing Costs

Monitor your proxy traffic from the dashboard to track usage by network and day. Since billing is pay as you go, you only pay for the GB you use. Set monthly GB caps on individual proxy users within the dashboard to prevent unexpected usage. For high-volume projects, the volume rates automatically lower your per-GB cost as your monthly traffic increases. Use compression and caching in your scraper to reduce proxy traffic and costs.

Questions

Can I use Colly with rotating proxies for scraping Google Search?

Yes, you can target US residential or ISP proxies for Google Search. Use country targeting (cc.us) and consider adding a session ID to maintain the same IP for a short series of requests, but rotate sessions frequently to avoid blocks. See our Google search proxies guide.

How do I handle CAPTCHAs when using Colly and rotating proxies?

Rotating proxies help reduce CAPTCHA frequency by distributing requests across many IPs. However, if you encounter CAPTCHAs, you need to implement a solving service or, better, adjust your crawling rate and patterns to be more polite. Read why CAPTCHAs appear.

My Colly scraper is getting 403 Forbidden errors through the proxy. What should I do?

A 403 from the target site indicates your request was detected and blocked. This could be due to the IP reputation, headers, or rate. Try switching to a different proxy network (e.g., from datacenter to residential), rotate IPs more frequently, and ensure your request headers (User-Agent, Accept-Language) look like a real browser. Our error 403 page has more tips.

Does Colly support proxy chaining with RotatingProxy?

Colly can be configured to use a single proxy gateway. Proxy chaining (sending traffic through multiple proxies sequentially) is not a service we provide or recommend, as it adds latency and complexity. Our gateway is a backconnect system that handles rotation internally.

How can I make sure my DNS queries go through the proxy?

When using the HTTP proxy (port 7070) with the standard `http.Transport`, DNS resolution for the target hostname is performed by the proxy server, preventing DNS leaks. With SOCKS5 (port 7071), ensure you are using the `Dial` method from the SOCKS5 dialer, which also routes DNS through the proxy. For details, see DNS resolution through the proxy.

Can I use the same Colly setup for scraping sites like Amazon or Instagram?

Absolutely. The configuration is the same; you only need to adjust the targeting options. For Amazon, you might target residential IPs in the country of the marketplace. For Instagram, mobile proxies can be very effective. Refer to our specific guides for Amazon proxies and Instagram proxies.

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.