From b2705e6a63b3d0c981a3c2c9d046a021bce18d5e Mon Sep 17 00:00:00 2001
From: Ophestra Umiker <cat@ophivana.moe>
Date: Mon, 14 Oct 2024 23:40:16 +0900
Subject: [PATCH] perf: cache constant hCaptcha site key responses

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

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
---
 captcha.go | 29 ++++++++++++++++-------------
 resp.go    | 21 +++++++++++++++++++++
 2 files changed, 37 insertions(+), 13 deletions(-)
 create mode 100644 resp.go

diff --git a/captcha.go b/captcha.go
index 73bc8c6..f2d517d 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 0000000..6f76399
--- /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}
+}
-- 
GitLab