diff options
| author | mo khan <mo@mokhan.ca> | 2025-04-30 12:23:57 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-04-30 12:23:57 -0600 |
| commit | 85b49396ce10aef9214803c5cfdf5c1d5cb93af9 (patch) | |
| tree | 301969c71e400a43c99f2fc27f06b1f7574b791d /pkg | |
| parent | ea841ab274630cff287a586d9799663a28c708fc (diff) | |
refactor: extract generic function to create and initialize any type
Diffstat (limited to 'pkg')
| -rw-r--r-- | pkg/pls/option.go | 10 | ||||
| -rw-r--r-- | pkg/web/cookie/new.go | 36 |
2 files changed, 25 insertions, 21 deletions
diff --git a/pkg/pls/option.go b/pkg/pls/option.go index bd717fa..fae002c 100644 --- a/pkg/pls/option.go +++ b/pkg/pls/option.go @@ -1,3 +1,13 @@ package pls +import "github.com/xlgmokha/x/pkg/x" + type Option[T any] func(T) T + +func New[T any](options ...Option[T]) T { + item := x.Default[T]() + for _, option := range options { + item = option(item) + } + return item +} diff --git a/pkg/web/cookie/new.go b/pkg/web/cookie/new.go index 08b796a..9aed2ab 100644 --- a/pkg/web/cookie/new.go +++ b/pkg/web/cookie/new.go @@ -8,40 +8,34 @@ import ( "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls" ) -type CookieOption pls.Option[*http.Cookie] - -func New(name, value string, options ...CookieOption) *http.Cookie { - cookie := &http.Cookie{ - Name: name, - Value: value, // TODO:: digitally sign the value - Path: "/", - HttpOnly: true, - Secure: true, - SameSite: http.SameSiteStrictMode, - Domain: env.Fetch("HOST", "localhost"), - } - - for _, option := range options { - cookie = option(cookie) - } - - return cookie +func New(name, value string, options ...pls.Option[*http.Cookie]) *http.Cookie { + options = append(options, With(func(c *http.Cookie) { + c.Name = name + c.Value = value // TODO:: digitally sign the value + c.Path = "/" + c.HttpOnly = true + c.Secure = true + c.SameSite = http.SameSiteStrictMode + c.Domain = env.Fetch("HOST", "localhost") + })) + + return pls.New[*http.Cookie](options...) } -func With(with func(*http.Cookie)) CookieOption { +func With(with func(*http.Cookie)) pls.Option[*http.Cookie] { return func(c *http.Cookie) *http.Cookie { with(c) return c } } -func WithSameSite(value http.SameSite) CookieOption { +func WithSameSite(value http.SameSite) pls.Option[*http.Cookie] { return With(func(c *http.Cookie) { c.SameSite = value }) } -func WithExpiration(expires time.Time) CookieOption { +func WithExpiration(expires time.Time) pls.Option[*http.Cookie] { return With(func(c *http.Cookie) { c.Expires = expires c.MaxAge = int(time.Until(expires).Seconds()) |
