Skip to content

Go CAPTCHA Integration

The following tutorial will guide you on how to integrate the TrustCaptcha CAPTCHA solution into your Go backend to retrieve and evaluate the CAPTCHA verification result.

If you only need the simple case, the package-level shortcut is the shortest path:

import "github.com/trustcomponent/trustcaptcha-go/v3"
result, err := trustcaptcha.GetVerificationResult("<your_api_key>", "<verification_token_from_the_client>")
if err != nil { /* handle error */ }
if !result.VerificationPassed || result.Score > 0.5 {
// possibly an automated request
}

For everything beyond that — custom timeouts, a proxy, a custom API host — use the configured constructor further down.


You should have already completed the following steps before you start with CAPTCHA validation in your Go backend.

  1. Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.

  2. Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.

  3. A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.

  4. Existing Go project: You need a Go project in which you want to integrate TrustCaptcha.

  5. Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.


Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your Go backend.

You can find the source code of our Go CAPTCHA integration on Github.

To use the TrustCaptcha Go library, you first need to add the corresponding dependencies to your project.

Terminal window
go get github.com/trustcomponent/trustcaptcha-go/v3@v3.0.0

You can find our TrustCaptcha Go package on https://pkg.go.dev/.

In the next step, retrieve the CAPTCHA result from our servers.

If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.

Use the TrustCaptcha class of our Go integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.

// Retrieving the verification result
verificationResult, err := trustcaptcha.GetVerificationResult("<your_api_key>", "<verification_token_from_the_client>")
if err != nil {
log.Printf("Failed to fetch verification result: %v", err)
http.Error(w, "Captcha verification failed", http.StatusInternalServerError)
return
}

Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the result validation overview.

// Act on the verification result
if !verificationResult.VerificationPassed || verificationResult.Score > 0.5 {
log.Println("Verification failed or bot score > 0.5 – possible automated request.")
}

If you need more control — a different API host, custom timeouts, or a proxy — construct a TrustCaptcha instance using New() with functional options. The package-level shortcut always uses the defaults.

import (
"time"
"github.com/trustcomponent/trustcaptcha-go/v3"
)
trustCaptcha, err := trustcaptcha.New(
"<your_api_key>",
trustcaptcha.WithApiHost("https://api.trustcomponent.com"),
trustcaptcha.WithConnectTimeout(3 * time.Second),
trustcaptcha.WithReadTimeout(5 * time.Second),
trustcaptcha.WithProxy("http://proxy.example.com:8080"),
)
if err != nil { /* handle error */ }
result, err := trustCaptcha.GetVerificationResult("<verification_token_from_the_client>")

A constructed *TrustCaptcha is immutable and safe for concurrent use: build it once at startup and share it across goroutines.

OptionTypeDefaultDescription
1st argument of New(...)string (required)Your API key. Must not be empty.
WithApiHost(host)stringhttps://api.trustcomponent.comOverride the API host. Useful for staging environments.
WithConnectTimeout(d)time.Duration3 * time.SecondConnect timeout.
WithReadTimeout(d)time.Duration5 * time.SecondRead timeout (response header timeout).
WithProxy(url)stringhttp.ProxyFromEnvironmentOverride the HTTP proxy URL. If unset, the default Go behaviour (HTTP_PROXY/HTTPS_PROXY env variables) is used.

Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.

Once you’ve decided on a policy, the library returns two typed errors that both implement the FailoverError marker:

  • *ServerUnreachableErrorhigh-trust (your backend cannot reach our servers). For example: allow the request and log the incident.
  • *ClientReportedServerUnreachableError (HTTP 412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
result, err := trustCaptcha.GetVerificationResult(token)
var serverUnreachable *trustcaptcha.ServerUnreachableError
var clientReported *trustcaptcha.ClientReportedServerUnreachableError
switch {
case errors.As(err, &serverUnreachable):
// Example: our servers are unreachable. Allow + log.
case errors.As(err, &clientReported):
// Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.
case err != nil:
// Other error.
default:
// Handle the result as you normally would (VerificationPassed, Score, your own policy).
}

When the result cannot be retrieved successfully the library returns a typed error. Use errors.As to discriminate between them.

Error typeWhen it is returned
*ApiKeyInvalidErrorThe API key was rejected (HTTP 403).
*VerificationTokenInvalidErrorThe verification token could not be parsed (malformed base64 / missing verificationId).
*VerificationNotFoundErrorNo verification was found for the given verification token (HTTP 404).
*VerificationNotFinishedErrorThe verification has not yet been completed by the user (HTTP 423).
*VerificationResultExpiredErrorThe result has expired and can no longer be retrieved (HTTP 410).
*VerificationResultRetrievalLimitReachedErrorThe result has reached its maximum retrieval count (HTTP 429).
*ServerUnreachableErrorThe TrustCaptcha server could not be reached at all (connection error / timeout). Implements the FailoverError marker. See Failover behavior.
*ClientReportedServerUnreachableErrorThe widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Implements the FailoverError marker. See Failover behavior.

The following example shows a possible implementation of TrustCaptcha in a Go backend.

In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the Go backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.

Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.

The complete example including source code can be found on Github.

package main
import (
"encoding/json"
"fmt"
"github.com/trustcomponent/trustcaptcha-go/v3"
"log"
"net/http"
)
type VerificationRequest struct {
VerificationToken string `json:"verificationToken"`
}
func postApiExample(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
var req VerificationRequest
// Parse the request body
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Retrieving the verification result
verificationResult, err := trustcaptcha.GetVerificationResult("<your_api_key>", req.VerificationToken)
if err != nil {
log.Printf("Failed to fetch verification result: %v", err)
http.Error(w, "Captcha verification failed", http.StatusInternalServerError)
return
}
// Act on the verification result
if !verificationResult.VerificationPassed || verificationResult.Score > 0.5 {
log.Println("Verification failed or bot score > 0.5 – possible automated request.")
}
// Send the verification result as response
if err := json.NewEncoder(w).Encode(verificationResult); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/api/example", postApiExample)
fmt.Println("Server is running on http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("could not listen on port 8080 %v", err)
}
}

Once you have integrated the TrustCaptcha widget into your frontend and the CAPTCHA result validation into your backend, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:

  • Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.

  • Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.

  • Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.

  • Failover behavior: Decide how your backend should behave when our service is temporarily unreachable. This is particularly important for high-availability flows where blocking real users during an outage is worse than letting through a small amount of unverified traffic. Learn more about failover behavior.

  • Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.