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 GitHubcaptcha - 图1open in new window and API documentation on pkg.go.devcaptcha - 图2open in new window.

Installation

The minimum requirement of Go is 1.16.

  1. 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.Captchaercaptcha - 图3open in new window works out-of-the-box with an optional captcha.Optionscaptcha - 图4open in new window, and the captcha.ValidText should be used to validate captcha tokens:

  • main.go
  • templates/home.tmpl
  1. package main
  2. import (
  3. "net/http"
  4. "github.com/flamego/captcha"
  5. "github.com/flamego/flamego"
  6. "github.com/flamego/session"
  7. "github.com/flamego/template"
  8. )
  9. func main() {
  10. f := flamego.Classic()
  11. f.Use(template.Templater())
  12. f.Use(session.Sessioner())
  13. f.Use(captcha.Captchaer())
  14. f.Get("/", func(t template.Template, data template.Data, captcha captcha.Captcha) {
  15. data["CaptchaHTML"] = captcha.HTML()
  16. t.HTML(http.StatusOK, "home")
  17. })
  18. f.Post("/", func(c flamego.Context, captcha captcha.Captcha) {
  19. if !captcha.ValidText(c.Request().FormValue("captcha")) {
  20. c.ResponseWriter().WriteHeader(http.StatusBadRequest)
  21. _, _ = c.ResponseWriter().Write([]byte(http.StatusText(http.StatusBadRequest)))
  22. } else {
  23. c.ResponseWriter().WriteHeader(http.StatusOK)
  24. _, _ = c.ResponseWriter().Write([]byte(http.StatusText(http.StatusOK)))
  25. }
  26. })
  27. f.Run()
  28. }
  1. <form method="POST">
  2. {{.CaptchaHTML}} <br>
  3. <input name="captcha">
  4. <button>Submit</button>
  5. </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.