From 2ed3cc0a1a05c32fb7ecc32b02f3245c078b4baf Mon Sep 17 00:00:00 2001 From: mo khan Date: Wed, 30 Apr 2025 15:06:55 -0600 Subject: refactor: delegate to cookie.Reset to overload with options --- pkg/web/cookie/new.go | 6 +++++- pkg/web/cookie/reset.go | 35 ++++++++++++----------------------- 2 files changed, 17 insertions(+), 24 deletions(-) (limited to 'pkg') diff --git a/pkg/web/cookie/new.go b/pkg/web/cookie/new.go index c255818..b809b4e 100644 --- a/pkg/web/cookie/new.go +++ b/pkg/web/cookie/new.go @@ -64,6 +64,10 @@ func WithSameSite(value http.SameSite) x.Option[*http.Cookie] { func WithExpiration(expires time.Time) x.Option[*http.Cookie] { return With(func(c *http.Cookie) { c.Expires = expires - c.MaxAge = int(time.Until(expires).Seconds()) + if expires.Before(time.Now()) { + c.MaxAge = -1 + } else { + c.MaxAge = int(time.Until(expires).Seconds()) + } }) } diff --git a/pkg/web/cookie/reset.go b/pkg/web/cookie/reset.go index 87e815e..cfb1830 100644 --- a/pkg/web/cookie/reset.go +++ b/pkg/web/cookie/reset.go @@ -8,29 +8,18 @@ import ( ) func Reset(name string) *http.Cookie { - return Clear(&http.Cookie{ - Name: name, - }) + return New( + name, + "", + WithExpiration(time.Unix(0, 0)), + WithPath("/"), + WithHttpOnly(true), + WithSecure(true), + WithSameSite(http.SameSiteDefaultMode), + WithDomain(env.Fetch("HOST", "localhost")), + ) } -func Expire(w http.ResponseWriter, r *http.Request, name string) { - cookie, err := r.Cookie(name) - if err != nil { - http.SetCookie(w, Reset(name)) - } else { - Clear(cookie) - http.SetCookie(w, cookie) - } -} - -func Clear(cookie *http.Cookie) *http.Cookie { - cookie.Value = "" - cookie.Expires = time.Unix(0, 0) - cookie.MaxAge = -1 - cookie.Path = "/" - cookie.HttpOnly = true - cookie.Secure = true - cookie.SameSite = http.SameSiteDefaultMode - cookie.Domain = env.Fetch("HOST", "localhost") - return cookie +func Expire(w http.ResponseWriter, name string) { + http.SetCookie(w, Reset(name)) } -- cgit v1.2.3