diff --git a/captcha.go b/captcha.go index 73bc8c6fef9b4f9d2b301da96d8f70fb8a06f8f0..f2d517d514d49c5f41f1f7d69333fe2023b58f15 100644 --- a/captcha.go +++ b/captcha.go @@ -4,21 +4,24 @@ import ( "github.com/gofiber/fiber/v3" ) -// Route to expose hCaptcha site key +type respHSiteKey struct { + Success bool `json:"success"` + SiteKey string `json:"hcaptcha_site_key"` +} + +// Route to expose hCaptcha site key. +// Returns a constant pre-generated response +// to avoid unnecessary allocations or serialisations func routeHCaptchaSiteKey(app *fiber.App, stub bool, siteKey string) { + var resp string if stub { - app.Get("/captcha", func(c fiber.Ctx) error { - return c.JSON(fiber.Map{ - "success": false, - "message": "hCaptcha is not enabled on this instance", - }) - }) + resp = mustConstResp(newMessage(false, "hCaptcha is not enabled on this instance.")) } else { - app.Get("/captcha", func(c fiber.Ctx) error { - return c.JSON(fiber.Map{ - "success": true, - "hcaptcha_site_key": siteKey, - }) - }) + resp = mustConstResp(respHSiteKey{true, siteKey}) } + + app.Get("/captcha", func(c fiber.Ctx) error { + c.Set("Content-Type", "application/json; charset=utf-8") + return c.SendString(resp) + }) } diff --git a/resp.go b/resp.go new file mode 100644 index 0000000000000000000000000000000000000000..6f763994f5759e0c3144312848cd57ead4ace751 --- /dev/null +++ b/resp.go @@ -0,0 +1,21 @@ +package main + +import "encoding/json" + +// pre-generate constant responses +func mustConstResp(a any) string { + if p, err := json.Marshal(a); err != nil { + panic(err.Error()) + } else { + return string(p) + } +} + +type respM struct { + Success bool `json:"success"` + Message string `json:"message"` +} + +func newMessage(success bool, message string) *respM { + return &respM{success, message} +}