captcha

The captcha middleware generates and validates captcha images for Flame instances, it relies on the session middleware.

You can read source code of this middleware on GitHubopen in new window and API documentation on pkg.go.devopen in new window.

Installation

go get github.com/flamego/captcha

Usage examples

WARNING

Examples included in this section is to demonstrate the usage of the captcha middleware, by no means illustrates the idiomatic or even correct way of doing user authentication.

The captcha.Captchaeropen in new window works out-of-the-box with an optional captcha.Optionsopen in new window, and the captcha.ValidText should be used to validate captcha tokens:

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(template.Templater())
	f.Use(session.Sessioner())
	f.Use(captcha.Captchaer())

	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()
}


















 



 










<form method="POST">
  {{.CaptchaHTML}} <br>
  <input name="captcha">
  <button>Submit</button>
</form>

Below is how it would look like in your browser for the above example:

Form with captcha

As the tooltip implies, single left-click on the captcha image would reload for a different one if characters in the current image is hard to recognize.