hcaptcha

The hcaptcha middleware provides hCaptchaopen in new window integration for Flame instances.

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

Installation

The minimum requirement of Go is 1.16.

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.Captchaopen in new window is used in combination with hcaptcha.Optionsopen in new window, and the hcaptcha.HCaptcha.Verify should be used to verify response tokens:

package main

import (
	"fmt"
	"net/http"

	"github.com/flamego/flamego"
	"github.com/flamego/hcaptcha"
	"github.com/flamego/template"
)

func main() {
	f := flamego.Classic()
	f.Use(template.Templater())
	f.Use(hcaptcha.Captcha(
		hcaptcha.Options{
			Secret: "<SECRET>",
		},
	))
	f.Get("/", func(t template.Template, data template.Data) {
		data["SiteKey"] = "<SITE KEY>"
		t.HTML(http.StatusOK, "home")
	})

	f.Post("/", func(w http.ResponseWriter, r *http.Request, h hcaptcha.HCaptcha) {
		token := r.PostFormValue("h-captcha-response")
		resp, err := h.Verify(token)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			_, _ = w.Write([]byte(err.Error()))
			return
		} else if !resp.Success {
			w.WriteHeader(http.StatusBadRequest)
			_, _ = w.Write([]byte(fmt.Sprintf("Verification failed, error codes %v", resp.ErrorCodes)))
			return
		}
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("Verified!"))
	})

	f.Run()
}




















 





 















<html>
<head>
  <script src="https://hcaptcha.com/1/api.js"></script>
</head>
<body>
  <form method="POST">
    <div class="h-captcha" data-sitekey="{{.SiteKey}}"></div>
    <input type="submit" name="button" value="Submit">
  </form>
</body>
</html>

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

Form with hCaptcha