recaptcha
The recaptcha middleware provides Google reCAPTCHA integration for Flame instances.
You can read source code of this middleware on GitHub and API documentation on pkg.go.dev.
Installation
go get github.com/flamego/recaptchaUsage examples
reCAPTCHA v3
The recaptcha.V3 is used in combination with recaptcha.Options for reCAPTCHA v3 integration, and the recaptcha.RecaptchaV3.Verify should be used to verify response tokens:
package main
import (
"fmt"
"net/http"
"github.com/flamego/flamego"
"github.com/flamego/recaptcha"
"github.com/flamego/template"
)
func main() {
f := flamego.Classic()
f.Use(template.Templater())
f.Use(recaptcha.V3(
recaptcha.Options{
Secret: "<SECRET>",
VerifyURL: recaptcha.VerifyURLGoogle,
},
))
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, re recaptcha.RecaptchaV3) {
token := r.PostFormValue("g-recaptcha-response")
resp, err := re.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()
}Because reCAPTCHA v3 is non-interruptive, you will not see any captcha image in the browser.
reCAPTCHA v2
The recaptcha.V2 is used in combination with recaptcha.Options for reCAPTCHA v2 integration, and the recaptcha.RecaptchaV2.Verify should be used to verify response tokens.
The following example is using the “I’m not a robot” Checkbox type of challenge:
package main
import (
"fmt"
"net/http"
"github.com/flamego/flamego"
"github.com/flamego/recaptcha"
"github.com/flamego/template"
)
func main() {
f := flamego.Classic()
f.Use(template.Templater())
f.Use(recaptcha.V2(
recaptcha.Options{
Secret: "<SECRET>",
VerifyURL: recaptcha.VerifyURLGoogle,
},
))
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, re recaptcha.RecaptchaV2) {
token := r.PostFormValue("g-recaptcha-response")
resp, err := re.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()
}Below is how it would look like in your browser for the above example:
