reCAPTCHA
How to solve reCAPTCHA v2 in Go
Go needs nothing beyond the standard library to talk to GateSolver. This guide builds a typed client around net/http and context so every solve has a hard deadline and cancels cleanly.
Why a typed client pays off in Go
The API speaks JSON in both directions, and Go's encoding/json works best with structs. Declaring the task and the reply as types gives you compile time checks on field names, which matters here: websiteURL and websiteKey are case sensitive in the JSON, and a typo would only surface as ERROR_INVALID_TASK_DATA at run time.
The second reason is context. Scrapers and test runners in Go usually already carry a context.Context with a deadline. Passing it into the solver means a cancelled crawl also stops its pending polls instead of leaving goroutines behind.
Define the request and reply types
One reply struct covers both endpoints. Fields that an endpoint does not send stay at their zero value, which keeps the client compact.
package gate
const TypeV2Proxyless = "ReCaptchaV2TaskProxyLess"
type RecaptchaV2 struct {
Type string `json:"type"`
WebsiteURL string `json:"websiteURL"`
WebsiteKey string `json:"websiteKey"`
Proxy string `json:"proxy,omitempty"`
}
type envelope struct {
ClientKey string `json:"clientKey"`
Task any `json:"task,omitempty"`
TaskID string `json:"taskId,omitempty"`
}
type reply struct {
ErrorID int `json:"errorId"`
ErrorCode string `json:"errorCode"`
ErrorDescription string `json:"errorDescription"`
TaskID string `json:"taskId"`
Status string `json:"status"`
Solution struct {
Token string `json:"gRecaptchaResponse"`
UserAgent string `json:"userAgent"`
} `json:"solution"`
}
The omitempty tags let the same envelope serve /createTask (with a task) and /getTaskResult (with a task id). The Proxy field is only filled when you switch the type to ReCaptchaV2Task.
Send requests with net/http
Every call goes through one method that attaches the context, decodes the body and converts an API error into a Go error value. Wrapping the API error code in a named type lets callers branch with errors.As later.
type APIError struct{ Code, Detail string }
func (e *APIError) Error() string { return e.Code + ": " + e.Detail }
type Client struct {
Key string
HTTP *http.Client
}
func (c *Client) post(ctx context.Context, path string, in envelope) (*reply, error) {
in.ClientKey = c.Key
raw, err := json.Marshal(in)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://gatesolver.com"+path, bytes.NewReader(raw))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
parsed := new(reply)
if decodeErr := json.NewDecoder(resp.Body).Decode(parsed); decodeErr != nil {
return nil, fmt.Errorf("decode %s: %w", path, decodeErr)
}
if parsed.ErrorID != 0 {
return nil, &APIError{parsed.ErrorCode, parsed.ErrorDescription}
}
return parsed, nil
}
Imports for this file are bytes, context, encoding/json, fmt and net/http. Give the http.Client a Timeout of around 30 seconds as a second guard; the context deadline covers the whole solve, the client timeout covers a single stuck request.
Poll with a ticker and a deadline
The solve method creates the task, then waits on two channels: a ticker that fires every three seconds and the context's Done channel. Whichever fires first decides what happens next.
func (c *Client) SolveV2(ctx context.Context, task RecaptchaV2) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 125*time.Second)
defer cancel()
created, err := c.post(ctx, "/createTask", envelope{Task: task})
if err != nil {
return "", err
}
tick := time.NewTicker(3 * time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return "", fmt.Errorf("solve %s: %w", created.TaskID, ctx.Err())
case <-tick.C:
r, err := c.post(ctx, "/getTaskResult", envelope{TaskID: created.TaskID})
if err != nil {
return "", err
}
switch r.Status {
case "ready":
return r.Solution.Token, nil
case "failed":
return "", errors.New("task failed, not charged")
}
}
}
}
A ticker is a better fit than time.Sleep in a loop because the select can react to cancellation in the middle of a wait. The 125 second ceiling sits just past the 120 seconds after which an unsolved task is closed as failed and left uncharged.
Call it from your program
c := &gate.Client{Key: os.Getenv("GATE_KEY"), HTTP: &http.Client{Timeout: 30 * time.Second}}
token, err := c.SolveV2(ctx, gate.RecaptchaV2{
Type: gate.TypeV2Proxyless, WebsiteURL: "https://accounts.example.org/register",
WebsiteKey: "6Lc_REGISTER_FORM_KEY",
})
With the token in hand, add it to the form values you post (url.Values{"g-recaptcha-response": {token}} plus the other fields), or pass it to a browser you control through chromedp or a similar tool. If you collect pages with Colly, the Colly collector's Post method accepts the same map.
Posting the form from Go
For a server rendered form, http.PostForm or a client with a cookie jar is all you need. Create the jar with cookiejar.New(nil), attach it to the http.Client you use for the target site (a different client from the one that talks to GateSolver), load the form page once so session cookies are set, then post the fields. Read the hidden inputs from the first response with an HTML parser such as golang.org/x/net/html, because CSRF tokens are usually required alongside the CAPTCHA answer.
Keep the two HTTP clients separate on purpose. The solver client only ever talks to one host and can reuse connections freely; the target client carries cookies, maybe a proxy transport, and a User-Agent header. If you set that header, the UserAgent field of the solution is a sensible value to use, since it describes the browser the token was produced under.
Testing the client without spending balance
The client is easy to unit test because the base URL is the only external dependency. Make it a field on Client instead of a constant, then point it at an httptest.Server in your tests. The fake server can answer /createTask with a fixed task id and /getTaskResult with processing twice before returning ready, which exercises the ticker path end to end.
Add one test per error branch as well: a reply with errorId 1 and ERROR_ZERO_BALANCE, a reply with status failed, and a server that never becomes ready so the context deadline fires. Shrink the timings in tests by making the poll interval a field too, otherwise the timeout test takes two minutes.
Retrying the right errors
Use errors.As to look inside the error and decide. ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE cost nothing and are worth one or two new attempts with a short backoff. ERROR_ZERO_BALANCE, ERROR_KEY_DENIED_ACCESS and ERROR_INVALID_TASK_DATA will fail the same way every time, so surface them immediately. The exponential backoff entry explains how to space retries without hammering the API.
When many goroutines solve at once, there is no concurrency cap to worry about, only the rate limit of 600 requests per minute per key. A buffered channel used as a semaphore keeps the number of in-flight polls predictable: send into it before a goroutine starts its solve and receive from it when the solve returns, and the channel's capacity becomes your ceiling. Pick a capacity that matches how many forms your target can reasonably receive, not how many the API could solve. For the field reference, see the reCAPTCHA v2 task page and the API docs.
Common questions
Does this client need any third-party Go modules?
No. It uses only the standard library: net/http, encoding/json, context, bytes, errors, fmt and time.
What Go version is required?
The any alias needs Go 1.18 or newer. Every current release works.
How do I cancel a solve from outside?
Cancel the parent context passed into SolveV2. The select loop returns at once with the context error.
Is a ticker better than time.Sleep for polling?
In Go it is, because the select statement can react to cancellation during the wait instead of sleeping through it.
How many tasks can run in parallel?
There is no limit on concurrent tasks. Keep total calls under 600 per minute for each API key.
Keep reading
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- CollyThe Go scraping framework built around a collector with callbacks, known for speed, low memory use and easy parallelism.
- Exponential backoffRetrying with delays that double each time plus random jitter, the standard response to 429 and 5xx errors.
- Solve Cloudflare Turnstile in GoA Go Turnstile client built around retries: a generic API helper, sentinel errors for transient failures and jittered backoff.