Cloudflare
How to solve Cloudflare Turnstile in Go
Long running Go services need a Turnstile client that recovers from the occasional failed task on its own. This guide builds one around clear error classes and a small retry policy.
Design goals
A Turnstile solve can end in four ways: a token, a temporary failure that is worth another try, a permanent problem with your setup, or cancellation from the caller. Code that treats all of these the same either retries forever on a missing API key or gives up on a hiccup that a second attempt would have fixed. The client in this guide makes the distinction explicit with a sentinel error, ErrTransient, that callers and the retry loop can test with errors.Is.
The second goal is less code per endpoint. A generic helper decodes any reply into the type you ask for, after first checking the shared error fields, so adding another task type later means adding a struct, not another HTTP function. Everything uses the standard library; the jitter uses math/rand/v2, available from Go 1.22.
Error classes
package turnstile
import (
"errors"
"slices"
)
// ErrTransient marks failures that a new task may fix.
var ErrTransient = errors.New("transient solver failure")
var retryable = []string{"ERROR_CAPTCHA_UNSOLVABLE", "ERROR_SERVICE_UNAVAILABLE", "TASK_FAILED", "TASK_TIMEOUT"}
type APIError struct{ Code, Message string }
func (e APIError) Error() string { return "gatesolver " + e.Code + ": " + e.Message }
func (e APIError) Is(target error) bool {
return target == ErrTransient && slices.Contains(retryable, e.Code)
}
Implementing Is on the error type is what lets errors.Is(err, ErrTransient) return true for some codes and false for others. ERROR_ZERO_BALANCE, ERROR_KEY_DENIED_ACCESS and ERROR_INVALID_TASK_DATA stay permanent, so the retry loop hands them straight back. TASK_FAILED and TASK_TIMEOUT are local codes for a task that ended without a token; both are free on the API side.
A generic API helper
const jsonMIME = "application/json"
type Solver struct {
Key string
HTTP *http.Client
}
func callAPI[T any](ctx context.Context, s *Solver, method string, body map[string]any) (T, error) {
var out T
body["clientKey"] = s.Key
buf, err := json.Marshal(body)
if err != nil {
return out, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://gatesolver.com/"+method, bytes.NewReader(buf))
if err != nil {
return out, err
}
req.Header.Set("Content-Type", jsonMIME)
res, err := s.HTTP.Do(req)
if err != nil {
return out, fmt.Errorf("%w: %v", ErrTransient, err)
}
defer res.Body.Close()
data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if err != nil {
return out, fmt.Errorf("%w: read body: %v", ErrTransient, err)
}
var head struct {
Failed int `json:"errorId"`
Code string `json:"errorCode"`
Why string `json:"errorDescription"`
}
if err := json.Unmarshal(data, &head); err != nil {
return out, err
}
if head.Failed != 0 {
return out, APIError{head.Code, head.Why}
}
return out, json.Unmarshal(data, &out)
}
Network errors are wrapped with ErrTransient, since a dropped connection is exactly the kind of thing a retry fixes. io.LimitReader caps the body at one megabyte, a cheap guard against a misbehaving proxy in between. This file imports bytes, context, encoding/json, fmt, io and net/http.
One attempt, then the retry policy
type taskCreated struct{ TaskID string `json:"taskId"` }
type taskState struct {
State string `json:"status"`
Solution struct{ Token, UserAgent string } `json:"solution"`
}
func (s *Solver) attempt(ctx context.Context, pageURL, siteKey string, meta map[string]string) (string, error) {
task := map[string]any{"type": "AntiTurnstileTaskProxyLess", "websiteURL": pageURL, "websiteKey": siteKey}
if len(meta) > 0 {
task["metadata"] = meta
}
c, err := callAPI[taskCreated](ctx, s, "createTask", map[string]any{"task": task})
if err != nil {
return "", err
}
for range 41 {
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(3 * time.Second):
}
st, err := callAPI[taskState](ctx, s, "getTaskResult", map[string]any{"taskId": c.TaskID})
if err != nil {
return "", err
}
if st.State == "ready" {
return st.Solution.Token, nil
}
if st.State == "failed" {
return "", APIError{"TASK_FAILED", c.TaskID}
}
}
return "", APIError{"TASK_TIMEOUT", c.TaskID}
}
The anonymous solution struct relies on encoding/json matching field names case insensitively, so token and userAgent land in Token and UserAgent without tags. for range 41 needs Go 1.22; on older versions write a classic counter loop.
func (s *Solver) Solve(ctx context.Context, pageURL, siteKey string, meta map[string]string) (string, error) {
pause := 2 * time.Second
var last error
for try := 1; try <= 3; try++ {
token, err := s.attempt(ctx, pageURL, siteKey, meta)
if err == nil || !errors.Is(err, ErrTransient) {
return token, err
}
last = err
jitter := time.Duration(rand.Int64N(int64(time.Second)))
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(pause + jitter):
}
pause *= 2
}
return "", fmt.Errorf("turnstile: gave up after 3 attempts: %w", last)
}
Three attempts with a pause that doubles (2, 4 seconds, plus up to a second of jitter) are enough for the transient cases without letting one widget hold a worker for ten minutes. The final error wraps the last cause, so a caller can still inspect it with errors.As.
Using the token
Pass the site key from the widget's data-sitekey (it starts with 0x4) and, when the page sets them, map[string]string{"action": "...", "cdata": "..."} as metadata. Then post the form with cf-turnstile-response set to the token, using a separate http.Client with a cookie jar for the target site. When a page builds its request in JavaScript, drive a browser with chromedp or a similar tool and inject the token there; the Node.js guide describes the callback pattern, which carries over directly.
Testing the retry path
Retry code is the part most likely to be wrong and least likely to be exercised in development, so give it tests. Make the base URL and the poll interval fields on Solver, then point the solver at an httptest.Server. A handler that answers createTask with ERROR_SERVICE_UNAVAILABLE on the first call and a task id on the second proves the loop recovers. A handler that always answers ERROR_ZERO_BALANCE proves the loop gives up after one call. A handler that never reports ready proves the timeout path, as long as the interval is shrunk to a few milliseconds in the test.
It is also worth one test that cancels the context halfway through the backoff pause. The select statement should return context.Canceled immediately; if the test hangs, a pause is being slept through somewhere.
Choosing retry numbers
Three attempts is a starting point, not a rule. For an interactive tool where a person waits on the result, two attempts and short pauses keep the worst case bearable. For an overnight batch, four attempts with longer pauses squeeze out a few more successes at no cost, since failed tasks are free. Whatever you choose, cap the total time per solve with the caller's context so one stubborn page cannot stall a whole worker.
Observability
Retries hide problems if nobody sees them. Count attempts per solve and expose the number through your metrics library, and log the task id with each failure. A sudden rise in TASK_FAILED for one site often means its widget configuration changed, for example a new action value that you are not sending yet. The guide on how to find Turnstile parameters shows how to re-read them.
Concurrency and limits
The solver is safe to share between goroutines: it holds only the key and an *http.Client, both safe for concurrent use. The API accepts any number of open tasks, while requests are limited to 600 per minute per key. Each solve polls about twenty times a minute, so a worker pool of a few dozen goroutines stays well within the limit; a buffered channel or golang.org/x/sync/semaphore keeps the pool size fixed.
Turnstile tokens are valid for 300 seconds and verify once, per Cloudflare's documentation, so post the form as soon as Solve returns. A solved task costs $0.84 per 1,000; failed attempts in the retry loop cost nothing. Fields and type names are on the Turnstile task page. For a typed reCAPTCHA client with a different structure, compare the reCAPTCHA v2 Go guide.
Common questions
Which Go version does this code need?
Go 1.22 or newer, for math/rand/v2 and range over an integer. Older versions need small changes to those two spots.
Which errors are retried?
Unsolvable tasks, service unavailable replies, failed or timed out tasks and network errors. Balance, key and task data errors are returned at once.
Are failed attempts charged?
No. Only solved tasks are charged, so the retry loop costs nothing for attempts that end without a token.
Why use a generic helper?
It checks the shared error fields once and decodes each endpoint into its own struct, so new task types need only a new type.
Can one Solver be shared by many goroutines?
Yes. It holds only the API key and an http.Client, both safe for concurrent use.
Keep reading
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Exponential backoffRetrying with delays that double each time plus random jitter, the standard response to 429 and 5xx errors.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- Solve reCAPTCHA v2 in GoA typed Go client for reCAPTCHA v2: request and response structs, net/http calls and a ticker bounded by a context deadline.