hugo-cms/handlers/ctx.go
2025-02-01 10:56:59 +11:00

58 lines
1.2 KiB
Go

package handlers
import (
"encoding/json"
"errors"
"github.com/gofiber/fiber/v2"
"lmika.dev/lmika/hugo-cms/models"
"log"
)
func GetUser(c *fiber.Ctx) models.User {
u, ok := c.Locals("user").(models.User)
if !ok {
panic(errors.New("user not found in context"))
}
return u
}
func GetSite(c *fiber.Ctx) models.Site {
s, ok := c.Locals("site").(models.Site)
if !ok {
panic(errors.New("no site in context"))
}
return s
}
func UpdatePrefCookie(c *fiber.Ctx, update func(prefs *models.PrefCookie)) {
cookie := GetPrefCookie(c)
update(&cookie)
setPrefCookie(c, cookie)
}
func GetPrefCookie(c *fiber.Ctx) models.PrefCookie {
prefCookieValue := c.Cookies(models.PrefCookieName)
if prefCookieValue == "" {
return models.PrefCookie{}
}
var prefCookie models.PrefCookie
err := json.Unmarshal([]byte(prefCookieValue), &prefCookie)
if err != nil {
return models.PrefCookie{}
}
return prefCookie
}
func setPrefCookie(c *fiber.Ctx, prefCookie models.PrefCookie) {
if prefJson, err := json.Marshal(prefCookie); err == nil {
c.Cookie(&fiber.Cookie{
Name: models.PrefCookieName,
Value: string(prefJson),
})
} else {
log.Printf("unable to save pref cookie: %v", err)
}
}