From c27b0a4e129388bd95958b4d9083c919ffab0ae1 Mon Sep 17 00:00:00 2001 From: "Gustavo L de Mello (Guz)" Date: Thu, 24 Oct 2024 20:28:02 -0300 Subject: [PATCH] feat(cookies): UnmarshalIfRequest helper/alias function --- handlers/pages/dashboard.templ | 10 ++-------- lib/cookies/cookies.go | 12 ++++++++++++ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/handlers/pages/dashboard.templ b/handlers/pages/dashboard.templ index 11b52ee..b7d7f27 100644 --- a/handlers/pages/dashboard.templ +++ b/handlers/pages/dashboard.templ @@ -2,7 +2,6 @@ package pages import ( "net/http" - "errors" "log" "strconv" @@ -32,15 +31,10 @@ func (p *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) { hasCookie := true - var c DashboardCookie - if err := cookies.UnmarshalRequest(r, &c); errors.Is(err, cookies.ErrNoCookie{}) { - hasCookie = false - c = DashboardCookie{Hello: "Hello world", Bool: true, Test: 69420} - } else if err != nil { + c := DashboardCookie{"hello world", true, 0} + if _, err := cookies.UnmarshalIfRequest(r, &c); err != nil { rerrors.InternalError(err).ServeHTTP(w, r) return - } else { - hasCookie = true } log.Print(hasCookie, c) diff --git a/lib/cookies/cookies.go b/lib/cookies/cookies.go index 0f1e027..645046e 100644 --- a/lib/cookies/cookies.go +++ b/lib/cookies/cookies.go @@ -73,6 +73,18 @@ func UnmarshalRequest(r *http.Request, v any) error { return Unmarshal(c, v) } +func UnmarshalIfRequest(r *http.Request, v any) (bool, error) { + if err := UnmarshalRequest(r, v); err != nil { + if _, ok := err.(ErrNoCookie); ok { + return false, nil + } else { + return true, err + } + } else { + return true, nil + } +} + func RerrUnmarshalCookie(err error) rerrors.RouteError { if e, ok := err.(ErrNoCookie); ok { return rerrors.MissingCookies([]string{e.name})