hcaptcha

The hcaptcha middleware provides hCaptchahcaptcha - 图1open in new window integration for Flame instances.

You can read source code of this middleware on GitHubhcaptcha - 图2open in new window and API documentation on pkg.go.devhcaptcha - 图3open in new window.

Installation

The minimum requirement of Go is 1.16.

  1. go get github.com/flamego/hcaptcha

Usage examples

WARNING

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

The hcaptcha.Captchahcaptcha - 图4open in new window is used in combination with hcaptcha.Optionshcaptcha - 图5open in new window, and the hcaptcha.HCaptcha.Verify should be used to verify response tokens:

  • main.go
  • templates/home.tmpl
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/flamego/flamego"
  6. "github.com/flamego/hcaptcha"
  7. "github.com/flamego/template"
  8. )
  9. func main() {
  10. f := flamego.Classic()
  11. f.Use(template.Templater())
  12. f.Use(hcaptcha.Captcha(
  13. hcaptcha.Options{
  14. Secret: "<SECRET>",
  15. },
  16. ))
  17. f.Get("/", func(t template.Template, data template.Data) {
  18. data["SiteKey"] = "<SITE KEY>"
  19. t.HTML(http.StatusOK, "home")
  20. })
  21. f.Post("/", func(w http.ResponseWriter, r *http.Request, h hcaptcha.HCaptcha) {
  22. token := r.PostFormValue("h-captcha-response")
  23. resp, err := h.Verify(token)
  24. if err != nil {
  25. w.WriteHeader(http.StatusBadRequest)
  26. _, _ = w.Write([]byte(err.Error()))
  27. return
  28. } else if !resp.Success {
  29. w.WriteHeader(http.StatusBadRequest)
  30. _, _ = w.Write([]byte(fmt.Sprintf("Verification failed, error codes %v", resp.ErrorCodes)))
  31. return
  32. }
  33. w.WriteHeader(http.StatusOK)
  34. _, _ = w.Write([]byte("Verified!"))
  35. })
  36. f.Run()
  37. }
  1. <html>
  2. <head>
  3. <script src="https://hcaptcha.com/1/api.js"></script>
  4. </head>
  5. <body>
  6. <form method="POST">
  7. <div class="h-captcha" data-sitekey="{{.SiteKey}}"></div>
  8. <input type="submit" name="button" value="Submit">
  9. </form>
  10. </body>
  11. </html>

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

Form with hCaptcha