hugo-cms/handlers/ctx.go

49 lines
1 KiB
Go
Raw Normal View History

2025-01-27 14:23:54 +11:00
package handlers
import (
2025-02-01 10:56:59 +11:00
"encoding/json"
2025-02-03 21:35:58 +11:00
"github.com/gofiber/fiber/v3"
2025-01-27 21:48:40 +11:00
"lmika.dev/lmika/hugo-cms/models"
2025-02-01 10:56:59 +11:00
"log"
2025-01-27 14:23:54 +11:00
)
2025-02-03 21:35:58 +11:00
func GetUser(c fiber.Ctx) models.User {
return fiber.Locals[models.User](c, "user")
2025-02-01 09:42:32 +11:00
}
2025-01-27 14:23:54 +11:00
2025-02-03 21:35:58 +11:00
func GetSite(c fiber.Ctx) models.Site {
return fiber.Locals[models.Site](c, "site")
2025-01-27 14:23:54 +11:00
}
2025-02-01 10:56:59 +11:00
2025-02-03 21:35:58 +11:00
func UpdatePrefCookie(c fiber.Ctx, update func(prefs *models.PrefCookie)) {
2025-02-01 10:56:59 +11:00
cookie := GetPrefCookie(c)
update(&cookie)
setPrefCookie(c, cookie)
}
2025-02-03 21:35:58 +11:00
func GetPrefCookie(c fiber.Ctx) models.PrefCookie {
2025-02-01 10:56:59 +11:00
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
}
2025-02-03 21:35:58 +11:00
func setPrefCookie(c fiber.Ctx, prefCookie models.PrefCookie) {
2025-02-01 10:56:59 +11:00
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)
}
}