main
1package cookie
2
3import (
4 "encoding/base64"
5 "fmt"
6 "net/http"
7 "time"
8
9 "github.com/xlgmokha/x/pkg/crypt"
10 "github.com/xlgmokha/x/pkg/x"
11)
12
13func With(with x.Configure[*http.Cookie]) x.Option[*http.Cookie] {
14 return x.With[*http.Cookie](with)
15}
16
17func WithName(name string) x.Option[*http.Cookie] {
18 return With(func(c *http.Cookie) {
19 c.Name = name
20 })
21}
22
23func WithValue(value string) x.Option[*http.Cookie] {
24 return With(func(c *http.Cookie) {
25 c.Value = value
26 })
27}
28
29func WithSignedValue(value string, signer crypt.Signer) x.Option[*http.Cookie] {
30 signature, _ := signer.Sign([]byte(value))
31 delimiter := "--"
32 encodedSignature := base64.URLEncoding.EncodeToString(signature)
33 return WithValue(fmt.Sprintf("%v%v%v", value, delimiter, encodedSignature))
34}
35
36func WithEncodedValue(data []byte, encoding *base64.Encoding) x.Option[*http.Cookie] {
37 return WithValue(encoding.EncodeToString(data))
38}
39
40func WithBase64Value(data []byte) x.Option[*http.Cookie] {
41 return WithEncodedValue(data, base64.URLEncoding)
42}
43
44func WithPath(value string) x.Option[*http.Cookie] {
45 return With(func(c *http.Cookie) {
46 c.Path = value
47 })
48}
49
50func WithHttpOnly(value bool) x.Option[*http.Cookie] {
51 return With(func(c *http.Cookie) {
52 c.HttpOnly = value
53 })
54}
55
56func WithSecure(value bool) x.Option[*http.Cookie] {
57 return With(func(c *http.Cookie) {
58 c.Secure = value
59 })
60}
61
62func WithDomain(value string) x.Option[*http.Cookie] {
63 return With(func(c *http.Cookie) {
64 c.Domain = value
65 })
66}
67
68func WithSameSite(value http.SameSite) x.Option[*http.Cookie] {
69 return With(func(c *http.Cookie) {
70 c.SameSite = value
71 })
72}
73
74func WithExpiration(expires time.Time) x.Option[*http.Cookie] {
75 return With(func(c *http.Cookie) {
76 c.Expires = expires
77 if expires.Before(time.Now()) {
78 c.MaxAge = -1
79 } else {
80 duration := time.Until(expires).Round(time.Second)
81 c.MaxAge = int(duration.Seconds())
82 }
83 })
84}