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

  1. go get github.com/flamego/captcha

Getting started

  1. <!-- templates/home.tmpl -->
  2. <form method="POST">
  3. {{.CaptchaHTML}} <br>
  4. <input name="captcha">
  5. <button>Submit</button>
  6. </form>
  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(session.Sessioner())
  12. f.Use(captcha.Captchaer())
  13. f.Use(template.Templater())
  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. }

Getting help

License

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