recaptcha

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: 8 Imported by: 0

README

reCAPTCHA

reCAPTCHA 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 reCAPTCHA?

reCAPTCHA 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 reCAPTCHA 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.

reCAPTCHA is widely used to protect websites from spam and abuse. It is developed by Google and is available in two versions: reCAPTCHA v2 and reCAPTCHA v3. reCAPTCHA v2 presents a challenge to the user, while reCAPTCHA v3 provides a score based on the user's interactions with the site.

For more information, you can refer to the reCAPTCHA Wikipedia page and the official reCAPTCHA documentation.

How to use reCAPTCHA with Iris?

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

  • Import the github.com/kataras/iris/v14/middleware/recaptcha package, which provides an Iris middleware for reCAPTCHA.
  • Use the recaptcha.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/recaptcha"
)

Next, we need to use the recaptcha.New function to create an iris.Handler. The function takes a recaptcha.Options value. Secret is required: a string that we can obtain from the reCAPTCHA website after creating an account and registering our website. FailureHandler is optional and runs when verification does not pass; the default replies with 429.

We can use the following code to create the handler:

// Create a recaptcha middleware with the secret key.
recaptchaMiddleware := recaptcha.New(recaptcha.Options{
    // Replace with your own secret key.
    Secret: "6Lf3WywUAAAAAJpArb8nW_LCL_PuPuokmEABFfgw",
})

The secret key can be found through: https://www.google.com/recaptcha. Please store it in a secure and private place.

Finally, we need to register the recaptcha 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 recaptcha middleware.
app.Use(recaptchaMiddleware)

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

Example

Here is a complete example of how to use reCAPTCHA with Iris:

package main

import (
    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/recaptcha"
)

// keys should be obtained by https://www.google.com/recaptcha
const (
    recaptchaPublic = "6Lf3WywUAAAAAKNfAm5DP2J5ahqedtZdHTYaKkJ6"
    recaptchaSecret = "6Lf3WywUAAAAAJpArb8nW_LCL_PuPuokmEABFfgw"
)

func showRecaptchaForm(ctx iris.Context, path string) {
    ctx.HTML(recaptcha.GetFormHTML(recaptchaPublic, path))
}

func main() {
    app := iris.New()

    // On both Get and Post on this example, so you can easily
    // use a single route to show a form and the main subject if recaptcha's validation result succeed.
    app.Handle("GET POST", "/", func(ctx iris.Context) {
        if ctx.Method() == iris.MethodGet {
            showRecaptchaForm(ctx, "/")
            return
        }

        result := recaptcha.SiteVerify(ctx, recaptchaSecret)
        if !result.Success {
            /* redirect here if you want or do nothing */
            ctx.HTML("<b> failed please try again </b>")
            return
        }

        ctx.Writef("succeed.")
    })

    app.Listen(":8080")
}

Documentation

Overview

Package recaptcha verifies the Google reCAPTCHA 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

This section is empty.

Variables

Client is the default `github.com/kataras/iris/v14/client#Client` instance which is used to send requests to the Google API. It is created with a 20s dial timeout.

Change Client only if you know what you're doing.

View Source
var DefaultFailureHandler = func(ctx *context.Context) {
	ctx.StopWithStatus(http.StatusTooManyRequests)
}

DefaultFailureHandler is the default handler that is fired on recaptcha failures. It stops the chain with 429 (Too Many Requests). See `Options.FailureHandler`.

Functions

func GetFormHTML

func GetFormHTML(dataSiteKey string, postActionRelativePath string) string

GetFormHTML can be used on pages where empty form is enough to verify that the client is not a "robot". i.e: GetFormHTML("public_key", "/contact") will return form tag which imports the google API script, with a simple submit button where redirects to the "postActionRelativePath".

The "postActionRelativePath" MUST use the `SiteVerify` or followed by the `New()`'s context.Handler (with the secret key this time) in order to validate if the recaptcha verified.

The majority of applications will use a custom form, this function is here for ridiculous simple use cases.

Example Code:

Method: "POST" | Path: "/contact"

func postContact(ctx *context.Context) {
	// [...]
	response := recaptcha.SiteVerify(ctx, recaptchaSecret)

	if response.Success {
		// [your action here, i.e sendEmail(...)]
	}

	ctx.JSON(response)
}

Method: "GET" | Path: "/contact"

func getContact(ctx *context.Context) {
	// render the recaptcha form
	ctx.HTML(recaptcha.GetFormHTML(recaptchaPublic, "/contact"))
}

func New

func New(opts Options) context.Handler

New returns a middleware that verifies the request by sending a response to the google's API(V2-latest), using the given Options.

Use `SiteVerify` to verify a request inside another handler if needed. A failed verification stops the chain with 429 (Too Many Requests) and stores the provider's response on the context, retrievable with `Get`.

Note(@kataras): the failure branch is not optional. This used to have no else at all, so a failed captcha answered an empty "200 OK" - which every client and every monitor reads as success - and discarded the reason in ErrorCodes.

Types

type Options

type Options struct {
	// Secret is the google's recaptcha secret key, obtained by
	// https://www.google.com/recaptcha. Used for communication between your
	// site and Google. Be sure to keep it a secret.
	// Required.
	Secret string `yaml:"Secret"`

	// FailureHandler, when set, is called instead of the default 429
	// (Too Many Requests) response after a failed verification.
	// Read the reason with `Get`.
	//
	// Defaults to DefaultFailureHandler.
	FailureHandler context.Handler `yaml:"-"`
}

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

type Response

type Response struct {
	ChallengeTS time.Time `json:"challenge_ts"`
	Hostname    string    `json:"hostname"`
	ErrorCodes  []string  `json:"error-codes"`
	Success     bool      `json:"success"`
}

Response is the google's recaptcha response as JSON.

func Get

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

Get returns the verification response of the current request, as stored by the middleware returned from `New`.

func SiteVerify

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

SiteVerify accepts context and the secret key(https://www.google.com/recaptcha) and returns the google's recaptcha response, if `response.Success` is true then validation passed.

Use `New` for middleware use instead.

Jump to

Keyboard shortcuts

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