hugo-cms/handlers/ctx.go

49 lines
1 KiB
Go
Raw Normal View History

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