captcha

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2023 License: MIT Imports: 10 Imported by: 0

README

captcha

GitHub Workflow Status Codecov GoDoc Sourcegraph

Package captcha is a middleware that provides captcha service for Flamego.

Installation

The minimum requirement of Go is 1.18.

go get github.com/flamego/captcha

Getting started

<!-- templates/home.tmpl -->
<form method="POST">
  {{.CaptchaHTML}} <br>
  <input name="captcha">
  <button>Submit</button>
</form>
package main

import (
	"net/http"

	"github.com/flamego/captcha"
	"github.com/flamego/flamego"
	"github.com/flamego/session"
	"github.com/flamego/template"
)

func main() {
	f := flamego.Classic()
	f.Use(session.Sessioner())
	f.Use(captcha.Captchaer())
	f.Use(template.Templater())

	f.Get("/", func(t template.Template, data template.Data, captcha captcha.Captcha) {
		data["CaptchaHTML"] = captcha.HTML()
		t.HTML(http.StatusOK, "home")
	})
	f.Post("/", func(c flamego.Context, captcha captcha.Captcha) {
		if !captcha.ValidText(c.Request().FormValue("captcha")) {
			c.ResponseWriter().WriteHeader(http.StatusBadRequest)
			_, _ = c.ResponseWriter().Write([]byte(http.StatusText(http.StatusBadRequest)))
		} else {
			c.ResponseWriter().WriteHeader(http.StatusOK)
			_, _ = c.ResponseWriter().Write([]byte(http.StatusText(http.StatusOK)))
		}
	})

	f.Run()
}

Getting help

License

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Captchaer

func Captchaer(opts ...Options) flamego.Handler

Captchaer returns a middleware handler that injects captcha.Captcha into the request context, which is used for generating and validating text in captcha images.

Types

type Captcha

type Captcha interface {
	// HTML returns the HTML content to display and refresh captcha images.
	HTML() template.HTML
	// ValidText validates the passed text against the secret text.
	ValidText(t string) bool
}

Captcha represents a captcha service and is used to validate text in captcha images.

type Options

type Options struct {
	// URLPrefix is the URL path prefix for serving captcha images. Default is
	// "/.captcha/".
	URLPrefix string
	// TextLength is the length of text to be generated in captcha images. Default
	// is 4.
	TextLength int
	// Width is the image width of captcha. Default is 240.
	Width int
	// Height is the image height of captcha. Default is 80.
	Height int
	// DPI is the image DPI of captcha. Default is 72.
	DPI int
}

Options contains options for the captcha.Captchaer middleware.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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