From ea841ab274630cff287a586d9799663a28c708fc Mon Sep 17 00:00:00 2001 From: mo khan Date: Wed, 30 Apr 2025 12:18:33 -0600 Subject: refactor: extract Option[T] and cleaner API for creating cookies --- pkg/web/cookie/cookie_test.go | 2 +- pkg/web/cookie/new.go | 24 +++++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) (limited to 'pkg/web') diff --git a/pkg/web/cookie/cookie_test.go b/pkg/web/cookie/cookie_test.go index 2f600f4..7256134 100644 --- a/pkg/web/cookie/cookie_test.go +++ b/pkg/web/cookie/cookie_test.go @@ -13,7 +13,7 @@ func TestCookie(t *testing.T) { t.Run("New", func(t *testing.T) { t.Run("returns a cookie pinned to the HOST", func(t *testing.T) { env.With(env.Vars{"HOST": "sparkle.example.com"}, func() { - cookie := New("name", "value", time.Now().Add(1*time.Minute)) + cookie := New("name", "value") assert.Equal(t, "sparkle.example.com", cookie.Domain) assert.True(t, cookie.HttpOnly) assert.True(t, cookie.Secure) diff --git a/pkg/web/cookie/new.go b/pkg/web/cookie/new.go index a3cb200..08b796a 100644 --- a/pkg/web/cookie/new.go +++ b/pkg/web/cookie/new.go @@ -10,12 +10,10 @@ import ( type CookieOption pls.Option[*http.Cookie] -func New(name, value string, expires time.Time, options ...CookieOption) *http.Cookie { +func New(name, value string, options ...CookieOption) *http.Cookie { cookie := &http.Cookie{ Name: name, Value: value, // TODO:: digitally sign the value - Expires: expires, - MaxAge: int(time.Until(expires).Seconds()), Path: "/", HttpOnly: true, Secure: true, @@ -29,3 +27,23 @@ func New(name, value string, expires time.Time, options ...CookieOption) *http.C return cookie } + +func With(with func(*http.Cookie)) CookieOption { + return func(c *http.Cookie) *http.Cookie { + with(c) + return c + } +} + +func WithSameSite(value http.SameSite) CookieOption { + return With(func(c *http.Cookie) { + c.SameSite = value + }) +} + +func WithExpiration(expires time.Time) CookieOption { + return With(func(c *http.Cookie) { + c.Expires = expires + c.MaxAge = int(time.Until(expires).Seconds()) + }) +} -- cgit v1.2.3