recaptcha

package module
v0.0.0-...-31f6fa7 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2020 License: MIT Imports: 5 Imported by: 0

README

recaptcha

MIT License go.dev reference Discord Chat

recaptcha is a package that handles verifying reCAPTCHA v2/v3 submissions in Go.

  • Validating a verification request, sending a verification request, and parsing a verification response are separated into individual functions.
  • Validates and double-checks all outgoing requests and incoming responses for errors.
  • Interoperable and made easy to work with both reCAPTCHA v2 and v3.
  • Uses valyala/fasthttp for sending reCAPTCHA request with an optional timeout.
  • Uses valyala/fastjson for parsing responses from the reCAPTCHA API.

Inspiration

Someone told me they were looking through reCAPTCHA packages online in Go and couldn't find a simple, idiomatic one.

This one's a bit overly optimized and uses two popular 3rd party libraries over the standard library, but here you go ¯_(ツ)_/.

Usage

go get github.com/lithdew/recaptcha
package main

import (
    "github.com/lithdew/recaptcha"
    "time"
)

func main() {
    req := recaptcha.Request{
        Secret: "", // Your reCAPTCHA secret.
        Response: "", // The reCAPTCHA response sent by the reCAPTCHA API.
        RemoteIP : "", // (optional) The remote IP of the user submitting the reCAPTCHA response.
    }

    // Verify the reCAPTCHA request.
    
    res, err := recaptcha.Do(req) 
    if err != nil {
    	panic(err)
    }

    if res.Success {
        println("reCAPTCHA attempt successfully verified!")
    } else {
        println("reCAPTCHA attempt failed!")
    }

    // Verify the reCAPTCHA request, and timeout after 3 seconds.

    res, err = recaptcha.DoTimeout(req, 3 * time.Second) 
    if err != nil {
    	panic(err)
    }

    if res.Success {
        println("reCAPTCHA attempt successfully verified!")
    } else {
        println("reCAPTCHA attempt failed!")
    }
}

Benchmarks

Take these with a grain of salt; network latency should sum up the majority of the benchmark results.

go test -bench=. -benchmem -benchtime=10s

goos: linux
goarch: amd64
pkg: github.com/lithdew/recaptcha
BenchmarkDo-8                        187          55273288 ns/op            1513 B/op         17 allocs/op
BenchmarkDoTimeout-8                 205          55503923 ns/op            1482 B/op         19 allocs/op
BenchmarkParallelDo-8               1500           7060534 ns/op            1386 B/op         17 allocs/op
BenchmarkParallelDoTimeout-8        1740           6752978 ns/op            1405 B/op         18 allocs/op

Documentation

Index

Constants

View Source
const Endpoint = "https://google.com/recaptcha/api/siteverify"

Endpoint to reCAPTCHA API.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client fasthttp.Client

Client wraps around a fasthttp.Client for verifying reCAPTCHA requests.

func (*Client) Do

func (c *Client) Do(params Request) (Response, error)

Do verifies a reCAPTCHA v2 or v3 attempt against reCAPTCHA's API. It errors if an error occurred pinging Google's servers, or on validating the response from Google's servers.

func (*Client) DoTimeout

func (c *Client) DoTimeout(params Request, timeout time.Duration) (Response, error)

DoTimeout verifies a reCAPTCHA v2 or v3 attempt against reCAPTCHA's API. It errors if either the request times out after timeout, or if an error occurred pinging Google's servers, or on validating the response from Google's servers.

type Request

type Request struct {
	// Required. The shared key between your site and reCAPTCHA.
	Secret string

	// Required. The user response token provided by the reCAPTCHA client-side integration on your site.
	Response string

	// Optional. The user's IP address.
	RemoteIP string
}

Request holds the payload to be sent to reCAPTCHA's API.

func (Request) MarshalTo

func (r Request) MarshalTo(req *fasthttp.Request)

MarshalTo fills a *fasthttp.Request with its parameters. Make sure to Validate() to validate this Request's parameters beforehand.

func (Request) Validate

func (r Request) Validate() error

Validate validates whether or not this request contains valid parameters. It returns an error should they be invalid. Validation right now has to do with checking whether or not required parameters are filled.

type Response

type Response struct {
	// Whether this request was a valid reCAPTCHA token for your site.
	Success bool `json:"success"`

	// (v3) The score for this request (0.0 - 1.0). 0.0 signifies high likelihood of a bot, and 1.0 signifies
	// otherwise.
	Score float64 `json:"score"`

	// (v3) The action name for this request (important to verify).
	Action string `json:"action"`

	// Timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ).
	ChallengeTS time.Time `json:"challenge_ts"`

	// The hostname of the site, or package name of the Android APK where the reCAPTCHA was solved.
	Hostname string `json:"hostname"`

	// Optional error codes.
	ErrorCodes []string `json:"error-codes"`
}

Response represents a response from reCAPTCHA's API.

func Do

func Do(params Request) (Response, error)

Do verifies a reCAPTCHA v2 or v3 attempt against reCAPTCHA's API. It errors if an error occurred pinging Google's servers, or on validating the response from Google's servers.

func DoTimeout

func DoTimeout(params Request, timeout time.Duration) (Response, error)

DoTimeout verifies a reCAPTCHA v2 or v3 attempt against reCAPTCHA's API. It errors if either the request times out after timeout, or if an error occurred pinging Google's servers, or on validating the response from Google's servers.

func Parse

func Parse(body []byte) (Response, error)

Parse parses either a reCAPTCHA v2 or v3 response from Google reCAPTCHA's API.

Jump to

Keyboard shortcuts

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