diff options
| author | mo khan <mo@mokhan.ca> | 2025-04-30 12:18:33 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-04-30 12:18:33 -0600 |
| commit | ea841ab274630cff287a586d9799663a28c708fc (patch) | |
| tree | 098cac4dd73524fd3d702e2e7535ad694be48b6c /pkg | |
| parent | 6dc20979d287652a849e32696fe3a805df1001ae (diff) | |
refactor: extract Option[T] and cleaner API for creating cookies
Diffstat (limited to 'pkg')
| -rw-r--r-- | pkg/web/cookie/cookie_test.go | 2 | ||||
| -rw-r--r-- | pkg/web/cookie/new.go | 24 |
2 files changed, 22 insertions, 4 deletions
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()) + }) +} |
