hcaptcha

package
v14.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 9 Imported by: 0

README

hCAPTCHA

hCAPTCHA protects a website from bots and spam by putting a challenge in front of the visitor. This middleware verifies that challenge on the server side, so a request that did not pass it never reaches your handler.

What is hCAPTCHA?

hCAPTCHA is a service that provides a widget that can be embedded in any web page. The widget displays a challenge that requires human intelligence to solve, such as identifying objects in images or typing words. The widget communicates with the hCAPTCHA server and verifies if the user has passed the challenge or not. If the user passes the challenge, the widget generates a token that can be used to validate the user's request on the server side.

hCAPTCHA is similar to reCAPTCHA, another popular service that offers similar functionality. However, hCAPTCHA claims to have some advantages over reCAPTCHA, such as:

  • Better privacy: hCAPTCHA does not track users across websites or collect personal data.
  • Better performance: hCAPTCHA uses less resources and loads faster than reCAPTCHA.
  • Better rewards: hCAPTCHA pays website owners for using their service and supports various causes and charities.

How to use hCAPTCHA with Iris?

To use hCAPTCHA with Iris, we need to do two things:

  • Import the github.com/kataras/iris/v14/middleware/hcaptcha package, which provides an Iris middleware for hCAPTCHA.
  • Use the hcaptcha.New function to create an iris.Handler and register it in our Iris app.

First, we need to install the Iris Web Framework, which contains the middleware too:

go get github.com/kataras/iris/v14@latest

Then, we need to import it in our main.go file:

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/hcaptcha"
    "github.com/kataras/iris/v14/rest/errors"
)

hcaptcha.New takes an hcaptcha.Options value. Secret is required; you get it from the hCAPTCHA dashboard after registering your site. FailureHandler runs when verification does not pass; the default replies with 429. RemoteIP and SiteKey are optional extra checks sent to siteverify.

We can use the following code to create the handler:

// Create a hcaptcha middleware with the secret key and a custom failure handler.
hcaptchaMiddleware := hcaptcha.New(hcaptcha.Options{
    // Replace with your own secret key.
    Secret: "0x123456789abcdef",
    FailureHandler: func(ctx iris.Context) {
        // The verification response, including any error codes,
        // is available from the request context.
        resp, _ := hcaptcha.Get(ctx)
        // The error code carries the 400 and stops the chain.
        errors.InvalidArgument.Detailf(ctx, "hcaptcha verification failed",
            "%v", resp.ErrorCodes)
    },
})

The secret key can be found through: https://dashboard.hcaptcha.com. Please store it on a secure and private place. To test hCAPTCHA on a local environment please read the following instructions at: https://docs.hcaptcha.com/#localdev.

Finally, we need to register the hcaptcha middleware in our Iris app. We can use the app.UseRouter and app.Use method to apply the middleware on every route. For example:

// Create an Iris app instance.
app := iris.New()

// Apply the hcaptcha middleware.
app.Use(hcaptchaMiddleware)

// Or apply the hcaptcha middleware to specific routes.
app.Get("/protected", hcaptchaMiddleware, func(ctx iris.Context) {
    // This route is protected by hcaptcha.
    ctx.WriteString("Hello, human!")
})

Documentation

Overview

Package hcaptcha verifies the hCaptcha answer that a form submission carries.

Its entry point is New(Options), which returns a Handler that calls SiteVerify and runs Options.FailureHandler when the answer does not pass. Read the stored Response with Get.

Index

Constants

View Source
const Script = "https://hcaptcha.com/1/api.js"

Script is the hCaptcha's javascript source file that should be incldued in the HTML head or body.

Variables

View Source
var (
	// DefaultFailureHandler is the default HTTP handler that is fired on hcaptcha failures.
	// See `Options.FailureHandler`.
	DefaultFailureHandler = func(ctx *context.Context) {
		ctx.StopWithStatus(http.StatusTooManyRequests)
	}
)
View Source
var HTMLForm = `` /* 174-byte string literal not displayed */

HTMLForm is the default HTML form for clients. It's totally optional, use your own code for the best possible result depending on your web application. See `ParseForm` and `RenderForm` for more.

View Source
var VerifyTimeout = 10 * time.Second

VerifyTimeout bounds how long a single verification call may take. Set it before the first verification; the HTTP client is built once, on first use, and later assignments have no effect.

Functions

func New

func New(opts Options) context.Handler

New returns a route middleware Handler which verifies the hcaptcha response of each incoming request against the given Options.

It calls the `SiteVerify` function and fires the "next" handler when the user completed the hcaptcha successfully, otherwise it calls Options.FailureHandler. The hcaptcha's `Response` (which contains any `ErrorCodes`) is saved on the Request's Context (see the `Get` package-level function).

Instructions at: https://docs.hcaptcha.com/.

func ParseForm

func ParseForm(dataSiteKey, postActionRelativePath string) string

ParseForm parses the `HTMLForm` with the necessary parameters and returns its result for render.

func RenderForm

func RenderForm(ctx *context.Context, dataSiteKey, postActionRelativePath string) error

RenderForm writes the `HTMLForm` to the Context's response writer. Use `ParseForm` or write your own HTML form for a custom result instead.

Types

type Options

type Options struct {
	// Secret is the hcaptcha secret key, from https://dashboard.hcaptcha.com/settings.
	// Required.
	Secret string `yaml:"Secret"`

	// FailureHandler if specified, fired when user does not complete hcaptcha successfully.
	// Failure and error codes information are kept as a `Response` value
	// in the request's context, retrieved through the `Get` package-level function.
	//
	// Defaults to DefaultFailureHandler, which writes a status code of
	// 429 (Too Many Requests) and no additional information.
	FailureHandler context.Handler `yaml:"-"`

	// RemoteIP is an optional check for siteverify:
	// the user's remote IP address, sent as the "remoteip" form field.
	//
	// Defaults to empty, not sent.
	RemoteIP string `yaml:"RemoteIP"`

	// SiteKey is an optional check for siteverify:
	// the sitekey form field you expect to see.
	//
	// Defaults to empty, not sent.
	SiteKey string `yaml:"SiteKey"`
}

Options is the configuration for the hcaptcha middleware. The zero value is valid but useless: Secret is required.

type Response

type Response struct {
	ChallengeTS string   `json:"challenge_ts"`
	Hostname    string   `json:"hostname"`
	ErrorCodes  []string `json:"error-codes,omitempty"`
	Success     bool     `json:"success"`
	Credit      bool     `json:"credit,omitzero"`
}

Response is the hcaptcha JSON response.

func Get

func Get(ctx *context.Context) (Response, bool)

Get returns the hcaptcha `Response` of the current request and reports whether was found or not.

func SiteVerify

func SiteVerify(ctx *context.Context, secret, remoteIP, siteKey string) (response Response)

SiteVerify accepts an Iris Context and a secret key (https://dashboard.hcaptcha.com/settings). It returns the hcaptcha's `Response`. The `response.Success` reports whether the validation passed. Any errors are passed through the `response.ErrorCodes` field.

The remoteIP and siteKey input arguments are optional.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL