← all guides

Setting up proxies in Go Colly: the colly proxy switcher explained

Why proxies show up in Colly projects

Colly is the scraping framework most Go developers reach for first, and for good reason. It’s small, it’s fast, and the callback model (OnHTML, OnRequest, OnError) keeps a crawler readable. What it doesn’t do out of the box is decide where your traffic comes from. Every request leaves from whatever IP your machine or server has.

There are legitimate reasons to route a Colly scraper through proxies, and it helps to be clear about them before touching code. You might need geographic reach, such as checking how a public price page renders for a visitor in Singapore versus Germany. You might be spreading a large, polite crawl across many addresses so that no single IP carries an unreasonable share of the load. Or your cloud provider’s IP range might be treated with suspicion by sites you’re allowed to read, and a different network class gets you a normal response.

What proxies are not is a license. They don’t make a scraper authorised, they don’t change what a site’s terms say, and nothing about them is undetectable or risk-free. I run proxy farms and production scrapers, and the honest summary after years of it is that proxies are plumbing.

This article is the written companion to the video. We’ll go through the colly proxy switcher from the ground up: the built-in round robin, how proxy URLs are formatted, how to write your own switcher when round robin isn’t enough, and how to combine proxies with rate limits, cookies and retries without hammering anyone. Every code sample is meant for public pages you’re permitted to fetch.

What the colly proxy switcher actually is

In Colly, “proxy switcher” is the name for a function with this signature: func(*http.Request) (*url.URL, error). That’s the same type Go’s http.Transport uses for its Proxy field. Colly exposes it through Collector.SetProxyFunc, and the colly/proxy package ships one ready-made implementation, RoundRobinProxySwitcher.

Every time the underlying transport is about to send a request, it calls your function and asks which proxy to use. Return a URL and the request goes through it. Return nil and it goes direct. Return an error and the request fails.

The nil case is more useful than it looks. Suppose your crawler also talks to an internal service on the same network, say a local queue or a metrics endpoint. Sending that traffic through a paid external proxy is wasteful at best and a leak of internal hostnames at worst. A switcher can check r.URL.Hostname() first, return nil for anything internal, and only fall through to the pool for public targets. Colly’s built-in switcher doesn’t do that, so mixed destinations mean a small wrapper.

Two details matter. First, the function is called per request, not once per collector, so you can vary the answer by target host, by request context, or by a counter. Second, connection reuse changes what “per request” means in practice. Go’s transport keeps connections alive and pools them by proxy and target. If your switcher hands out proxy A and then proxy B, you get two separate pools, and a request that lands on a pooled connection doesn’t open a new tunnel.

There’s also the simpler SetProxy("http://host:port"), which pins the whole collector to one proxy. Use it when you have a single gateway endpoint that rotates on the provider side. Use SetProxyFunc when you hold a list and want to choose yourself.

The minimal setup with round robin

Install Colly v2 first:

go get github.com/gocolly/colly/v2

Here’s the smallest useful program. It creates a collector, builds a round robin switcher from three proxy URLs, and visits a page.

package main

import (
    "log"

    "github.com/gocolly/colly/v2"
    "github.com/gocolly/colly/v2/proxy"
)

func main() {
    c := colly.NewCollector(
        colly.UserAgent("ExampleBot/1.0 (+https://example.com/bot)"),
    )

    rp, err := proxy.RoundRobinProxySwitcher(
        "http://user:[email protected]:8080",
        "http://user:[email protected]:8080",
        "socks5://user:[email protected]:1080",
    )
    if err != nil {
        log.Fatal(err)
    }
    c.SetProxyFunc(rp)

    c.OnResponse(func(r *colly.Response) {
        log.Println(r.Request.URL, r.StatusCode)
    })

    c.Visit("https://books.toscrape.com/")
}

The addresses are documentation-range placeholders, so swap in your own. The switcher parses each string up front and returns an error if any of them is malformed, which is why you check err. Round robin means request one goes to the first proxy, request two to the second, and so on, wrapping around.

That simplicity has a consequence in async mode. The counter is shared by every goroutine, so the order in which proxies are handed out follows the order in which requests reach the transport, not the order in which you queued them. If you queue ten URLs and expect URL three to use proxy three, you’ll be disappointed. Assignment is even across the pool over time, but not predictable per URL.

Notice the user agent says who I am and gives a contact URL. Colly’s default is a generic string, and an honest, identifiable agent is part of running a scraper that site owners can reach if something goes wrong. Also notice the target: books.toscrape.com is a sandbox built for scraping practice. Test your proxy plumbing against targets like that, not against a real site’s production pages.

Verifying that traffic really leaves through the proxy

Never assume the switcher works. Prove it. The quickest check is an IP echo endpoint: request it through each proxy and compare the answers to your own address.

c := colly.NewCollector()
rp, _ := proxy.RoundRobinProxySwitcher(proxyList...)
c.SetProxyFunc(rp)
c.AllowURLRevisit = true

c.OnResponse(func(r *colly.Response) {
    log.Printf("egress IP: %s", string(r.Body))
})

for i := 0; i < len(proxyList)*2; i++ {
    c.Visit("https://api.ipify.org/")
}

Two things trip people up here. Colly skips URLs it has already visited, so without AllowURLRevisit = true you’d see one response and wonder where the rest went. And with round robin over N proxies, you want at least 2N requests so every address shows up twice, in order. If the same IP appears every time, either the proxy function isn’t being applied, or your provider is a rotating gateway that hands out a new address only on its own schedule.

Beyond the IP, check what else the exit tells you. A residential or mobile proxy should resolve to a consumer ISP’s ASN. A datacenter proxy will show a hosting company. Any public ASN lookup will tell you. If you paid for one class and the exit belongs to another, that’s a fact worth knowing before you build on it.

Also measure latency and failure rate over a sample. Ten requests tells you very little. A few hundred, spread across a day, starts to tell you something. I’m not quoting provider numbers here because this article doesn’t show a test, and a number without a test is just marketing.

Proxy URL formats, auth and the traps in them

The switcher accepts three schemes: http, https and socks5. The format is scheme://user:pass@host:port.

Special characters in passwords. If a password contains @, :, / or #, the URL parser will misread it. Percent-encode the credentials, or build the URL with url.UserPassword and let Go do it:

u := &url.URL{
    Scheme: "http",
    User:   url.UserPassword("customer-abc", "p@ss:word/1"),
    Host:   "gw.example-provider.com:7000",
}

Then pass u.String() to the switcher. Many providers put session or country parameters in the username, for example a suffix that pins a sticky session. Treat that username as an opaque string from the provider’s docs and don’t guess at formats.

HTTP versus SOCKS5. An http proxy receives the request and, for https targets, a CONNECT request that opens a tunnel. A SOCKS5 proxy is lower level and doesn’t care about the protocol above it. For ordinary scraping either works. Pick whichever your provider documents best. Go’s standard transport hands the hostname to SOCKS5 proxies for resolution on the far side, which keeps DNS lookups from originating on your machine, but confirm that with a packet capture if it matters for your setup.

Credentials in logs. Colly’s debugger and your own logging will print proxy URLs if you’re careless. Log the host, never the userinfo. Keep the list in environment variables or a secrets manager, not in source control. I’ve seen more proxy credentials leak through committed config files than through any network attack.

IP allow-listing. Some providers authenticate by your source IP instead of a password. Then the URL has no userinfo at all, and a scraper that moves between machines suddenly gets 407 errors or refused connections. Check which mode you bought.

Writing your own switcher

Round robin is fine for a pool of identical proxies. It’s the wrong tool when proxies differ in quality, when some die mid-run, or when you want one site to always see the same exit. Because a switcher is only a function, custom logic is short. Colly even exports the type as colly.ProxyFunc.

Here’s one that pins each target host to a single proxy by hashing the hostname. Requests to the same site share an exit, which keeps a cookie session coherent, while different sites spread across the pool.

func hostPinned(proxies []*url.URL) colly.ProxyFunc {
    return func(r *http.Request) (*url.URL, error) {
        h := fnv.New32a()
        h.Write([]byte(r.URL.Hostname()))
        idx := int(h.Sum32() % uint32(len(proxies)))
        return proxies[idx], nil
    }
}

Wire it up with c.SetProxyFunc(hostPinned(list)). The modulo happens on the unsigned value before the conversion, which avoids a negative index on 32-bit builds.

A few other patterns are worth knowing. A weighted switcher repeats the better proxies in the slice so they get a proportionally larger share. A health-aware one keeps a mutex-guarded set of proxies that are cooling off after failures, skips them, and returns an error if the whole pool is cooling. A per-request override reads a value from r.Context() to choose the exit, which is handy when a retry should deliberately use a different proxy.

One rule applies to all of them. With async mode on, your function is called from many goroutines at once, so any shared state needs a mutex or atomics. A data race in a proxy chooser is a miserable bug to chase, because it shows up as occasional wrong-proxy requests rather than a crash.

Provider-side rotation versus your own list

Two models dominate. With a list, you hold a set of ip:port endpoints and the switcher chooses. With a gateway, you connect to one hostname and the provider assigns the exit, either changing it per request or holding a sticky session for a period controlled by a parameter in your credentials.

For a gateway, you don’t need a switcher at all. c.SetProxy("http://user:[email protected]:7000") is enough, and rotation is the provider’s job. The mistake I see is stacking both: a round robin over five copies of the same gateway URL.

The trade-offs, concretely. A list is predictable: you control assignment and can see exactly which exit failed, and you also own the health tracking and the churn when addresses go dead. A gateway with per-request rotation is less code, but you can’t keep a session on one IP, so a page that sets a cookie on request one may see request two arrive from somewhere else. A gateway with sticky sessions is the middle path. You get one exit for a window, then it changes. Window length and behavior are provider-specific, so read the docs and measure it rather than trusting a marketing page.

Running our own farms taught me one thing about the supply side: an address that was fine yesterday can be reassigned or blocklisted today, especially on mobile carrier networks where many subscribers share addresses. A pool is a living thing. Build the client so that a dead or degraded proxy is a routine event, not an outage, and so that you find out about it from your own logs before a customer finds out from missing data.

Choosing between datacenter, residential and mobile

The three classes are defined by who the address belongs to, and that’s what everything else follows from.

Datacenter. Addresses from hosting companies. They’re cheap, fast and plentiful, and anyone who looks up the ASN can see they’re hosting ranges. Many sites apply extra scrutiny to those ranges because a large share of automated traffic comes from them. For sites that don’t care, such as open data portals, public APIs, your own properties and sandboxes, datacenter is usually the sensible starting point.

Residential. Addresses assigned by consumer ISPs, reached through devices in the provider’s network. The sourcing is the part to ask about. Whether the people behind those devices knowingly opted in is an ethics and supply-chain question, and I won’t vouch for any provider’s answer without seeing evidence of it.

Mobile. Carrier addresses, typically shared among many subscribers behind carrier-grade NAT, so reputation is pooled. Because blocking one address can affect many real users, some sites are more cautious about how they treat them. That’s a description of how the network works, not a promise about any site’s behavior. Nothing here is unblockable, and any vendor claiming otherwise is selling you something.

Pricing differs by class. Residential and mobile are usually metered by bandwidth, datacenter often by address or by bandwidth.

My decision rule is simple. Start with the cheapest class that works for a target you’re permitted to read. Move up a class only when you have a legitimate need, such as locale-specific content, and a measured problem, such as a consistent refusal from datacenter ranges on a page you’re allowed to fetch. And if a site’s terms prohibit automated access, changing network class doesn’t change that answer.

Concurrency, limits and why more proxies don’t mean more speed

Colly’s async mode plus a LimitRule is where proxies and politeness meet.

c := colly.NewCollector(
    colly.Async(true),
    colly.AllowedDomains("books.toscrape.com"),
)
c.SetRequestTimeout(30 * time.Second)
c.Limit(&colly.LimitRule{
    DomainGlob:  "*",
    Parallelism: 2,
    Delay:       1 * time.Second,
    RandomDelay: 500 * time.Millisecond,
})

// ... register callbacks, call c.Visit(...)
c.Wait()

Parallelism caps concurrent requests per matching domain. Delay is the pause between requests to that domain, and RandomDelay adds a random extra up to that value. Don’t forget c.Wait(), or your program exits before async work finishes.

The limit is per domain, not per proxy. Adding twenty proxies doesn’t mean you should raise the rate against a site by twenty. The load a site experiences is the load it experiences, regardless of how many source addresses it arrives from. If a site would reject your request rate from one address, spreading that same rate across many addresses is the pattern defenders classify as evasion, and it’s poor practice besides. Treat the rate as a property of the target, set from what the site can reasonably bear, and use extra proxies for geography or for isolation, not to outrun a limit.

Other guardrails worth setting: colly.AllowedDomains so a stray link can’t send the crawler somewhere you never intended, colly.MaxDepth so a crawl can’t wander forever, and colly.CacheDir so re-runs don’t refetch pages you already have. A request timeout matters more with proxies than without, because a dead proxy can otherwise hold a worker for a long time.

Errors, retries and reading status codes

With proxies in the path, failures come from two places: the proxy and the target. Your error handling needs to tell them apart, because the right response differs.

A status code of 0 with an error is a transport failure: connection refused, timeout, TLS problem. It’s usually the proxy or the network, and hopping to another proxy is reasonable. A 407 means proxy authentication failed. Retrying won’t help, so fix credentials or allow-listing and stop. A 429 is the target telling you to slow down. Back off, honor a Retry-After header if present, and lower your rate, because switching IP doesn’t address the message. A 403 is ambiguous. It could be a path the site doesn’t want automated, or a reputation problem with the exit, and either way you shouldn’t loop on it. A 5xx is often transient on the target’s side, and a small, delayed retry is fine.

A bounded retry looks like this:

c.OnError(func(r *colly.Response, err error) {
    if r.StatusCode == 407 {
        log.Fatal("proxy auth failed, check credentials")
    }
    n, _ := strconv.Atoi(r.Ctx.Get("retries"))
    if n >= 2 || r.StatusCode == 403 || r.StatusCode == 429 {
        log.Printf("giving up on %s: %d %v", r.Request.URL, r.StatusCode, err)
        return
    }
    r.Ctx.Put("retries", strconv.Itoa(n+1))
    time.Sleep(time.Duration(n+1) * 3 * time.Second)
    r.Request.Retry()
})

Two retries with growing delays, and no retry at all on 403 or 429. When Colly retries, a round robin switcher naturally sends the next attempt through the next proxy, which suits transport errors. Log every give-up with the URL and status, so you can review what your scraper is being refused, instead of quietly retrying it into a ban.

Here’s a worked example of what that policy costs you. Say you have three proxies in a round robin and one of them is dead. In a simple sequential run, every third request is assigned to the dead proxy and fails with a transport error. The handler sleeps three seconds, then retries, and the counter has moved on, so the retry lands on a healthy proxy and succeeds. The result: every page still arrives, but a third of them are delayed by three seconds, and your logs fill with errors that look alarming until you notice they cluster on one address. Now make two of the three dead. A retry can land on the other dead proxy, and after two retries some pages are abandoned. Bounded retries hide a single bad proxy well and a mostly-bad pool poorly, so you want to know which situation you’re in.

One caveat on the retry handler above. In async mode the next-proxy guarantee weakens, because other goroutines pull from the same counter between your failure and your retry. The retry usually lands on a different proxy, but not always. If a retry must avoid the failed exit, use the per-request override pattern and record the failed proxy in the context.

How detection systems see a scraper, and how a compliant one stays clean

It helps to understand the other side, because most “blocked” experiences are a scraper behaving in ways defenders can see plainly. This is a description of how these systems work, not a way around them.

Sites typically combine several signals. IP reputation and network class: hosting ranges get more scrutiny than consumer ISPs, and an address with a history of abusive traffic carries that history. Rate and pattern: a steady, machine-regular request cadence, or a burst that no human reader produces, stands out. Client consistency: a request claiming to be a desktop browser while sending a header set and TLS handshake that no browser produces is internally inconsistent, and that inconsistency is itself a signal. Session behavior: cookies that appear from many addresses at once, or never at all. Challenges: JavaScript checks and captchas that a plain HTTP client can’t complete.

Colly is an HTTP client. It doesn’t run JavaScript, and it isn’t a browser. If a page requires JavaScript to render the data you’re allowed to read, that’s a job for a different tool, or better, for an official API or data feed.

When you hit a captcha or challenge page, read it as the site’s answer. It’s saying that path isn’t meant for automation, and a compliant scraper stops there and looks for permission, an API, or a data partnership.

What keeps a scraper clean is mostly dull. Colly’s IgnoreRobotsTxt defaults to true, so set c.IgnoreRobotsTxt = false and actually honor robots.txt. Send an honest user agent with contact details. Rate limit conservatively. Cache aggressively. Fetch off-peak where you can. Read the terms of service before you build, not after. None of that guarantees you won’t be blocked, but it removes most of the reasons a site would want to.

Cookies, sessions and rotating exits

Colly keeps a cookie jar on the collector, and every request shares it. Combine that with a rotating proxy and you get a quiet problem: one session cookie now appears to arrive from several IPs in quick succession. Some sites invalidate the session, some serve different content, and some simply log it as odd.

For public, stateless pages the fix is to not carry state. c.DisableCookies() removes the question entirely, and most listing and article pages work fine without it.

When you do need a session, keep it on one exit. The hostPinned switcher from earlier does that per site. The stricter version is one collector per proxy, each with its own jar, fed from a shared job channel:

func worker(p string, jobs <-chan string, wg *sync.WaitGroup) {
    defer wg.Done()
    c := colly.NewCollector()
    c.SetProxy(p)
    // register callbacks here
    for u := range jobs {
        c.Visit(u)
    }
}

Start one goroutine per proxy and each holds a consistent identity from the site’s point of view.

Build each worker with NewCollector rather than c.Clone(). As far as I can tell from the source, a clone shares the underlying HTTP backend with the original, so setting a proxy on the clone can change the original’s behavior too. If you rely on it, verify with the egress IP check from earlier instead of taking my word for it.

One more habit: when a proxy is retired, retire its collector and its cookies together.

The pinned approach has its own failure mode worth planning for. With hostPinned, the mapping from host to proxy depends on the length of the slice. If you remove a dead proxy from the list, the modulo changes and most hosts suddenly map to a different exit, so every live session jumps IPs at once. Two ways around it: keep dead proxies in the slice and have the switcher fall through to the next live entry only for hosts that were pinned to them, or accept that a session break on pool changes is the price and design the crawl to log in again cleanly. Either is defensible. Silently reshuffling everything is the one that bites.

Cost, bandwidth and testing a pool before you trust it

Metered proxies charge for bytes, so waste is money. Colly won’t pull images unless you visit those URLs, but retries, duplicate fetches and oversized pages add up. Go’s transport negotiates gzip by default, which helps. The bigger wins are CacheDir, tight URLFilters, and the bounded retry policy above, since an unbounded retry loop on a metered proxy is a bill you didn’t plan for.

To see how it compounds, take a purely illustrative case: a page that weighs 500 KB and consistently fails after the body has been downloaded, for example a target that returns a full error page. With two retries allowed, that one URL costs three downloads, about 1.5 MB, for zero useful data. That’s another reason 403 and 429 get no retry in the handler above, and why give-ups are logged with the URL: a cluster of them tells you to fix the crawl, not to spend more bandwidth on it.

Before you scale anything, test the pool as a system. My checklist:

  1. Confirm the egress IP differs from yours and rotates as expected.
  2. Look up the ASN and check it matches the class you paid for.
  3. Sample latency and success rate across several hours, not several minutes.
  4. Record every 407, timeout and refusal, with the target.
  5. Only then compare against alternatives, using your own numbers.

Then keep checking in production. A small health check per proxy is enough to drop failures automatically:

func alive(p *url.URL) bool {
    client := &http.Client{
        Timeout:   10 * time.Second,
        Transport: &http.Transport{Proxy: http.ProxyURL(p)},
    }
    resp, err := client.Get("https://api.ipify.org/")
    if err != nil {
        return false
    }
    defer resp.Body.Close()
    return resp.StatusCode == 200
}

Run it on a timer, and cool a proxy off after three failures in a row. That gives you a pool that repairs itself, and it gives you a record you can point to when you judge a provider.

What to do differently on Monday

Here’s the short version of everything above, in the order I’d apply it.

Start by deciding who rotates. One gateway URL means SetProxy, and a list of endpoints means SetProxyFunc, either the built-in round robin or your own function. Never stack both. Next, prove the setup: run the IP echo check with AllowURLRevisit on, see every address twice, and look up the ASN.

Then fix your credentials handling. Build URLs with url.UserPassword, keep secrets out of source control, and never log userinfo. Set an honest identity and good manners too: a truthful user agent with a contact URL, IgnoreRobotsTxt = false, AllowedDomains, and a LimitRule sized to the target, not to your proxy count.

Handle errors by type. Retry transport failures a couple of times with backoff, treat 429 as a request to slow down, and treat 403 as a reason to stop and reread the site’s rules. Keep sessions coherent by disabling cookies for stateless pages, pinning a site to one exit, or running one collector per proxy. Finally, test before you spend: run the pool through the five-step checklist and keep the results.

And the boundaries, plainly. Don’t collect personal data. Don’t go after paywalled content. Don’t treat a captcha as an obstacle to route around, because it’s the site declining automation on that path. Don’t expect any proxy class to make you immune to blocking, since none does, and don’t write scrapers whose only plan is to outlast a site’s refusal.

If you want to see this running against a sandbox site, with the egress checks and the failure handling live, the video walks through it step by step. More guides on choosing and testing proxies, and on scraping cleanly at scale, are on the Proxy Scraping home page.

Get new guides and videos first — join the Telegram channel.

proxies
Need proxies that survive the block wall?

Singapore Mobile Proxy runs real 4G/5G mobile IPs on rotating SIMs — the carrier-grade addresses most of these targets still trust.

see plans →
read on
More scraping guides

The rest of the field manual: target-site playbooks, library walkthroughs, provider reviews, and anti-bot troubleshooting.

browse all guides →