Skip to content
Snippets Groups Projects
Verified Commit b2705e6a authored by Ophestra's avatar Ophestra
Browse files

perf: cache constant hCaptcha site key responses


This reduces the unnecessary JSON serialisation work each time this endpoint is called.

Signed-off-by: default avatarOphestra Umiker <cat@ophivana.moe>
parent 9b8e2fc4
Branches
Tags
1 merge request!3Upgrade to Fiber v3 and implement hCaptcha protection
...@@ -4,21 +4,24 @@ import ( ...@@ -4,21 +4,24 @@ import (
"github.com/gofiber/fiber/v3" "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) { func routeHCaptchaSiteKey(app *fiber.App, stub bool, siteKey string) {
var resp string
if stub { if stub {
app.Get("/captcha", func(c fiber.Ctx) error { resp = mustConstResp(newMessage(false, "hCaptcha is not enabled on this instance."))
return c.JSON(fiber.Map{
"success": false,
"message": "hCaptcha is not enabled on this instance",
})
})
} else { } else {
resp = mustConstResp(respHSiteKey{true, siteKey})
}
app.Get("/captcha", func(c fiber.Ctx) error { app.Get("/captcha", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{ c.Set("Content-Type", "application/json; charset=utf-8")
"success": true, return c.SendString(resp)
"hcaptcha_site_key": siteKey,
}) })
})
}
} }
resp.go 0 → 100644
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}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment