-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.go
93 lines (79 loc) · 1.77 KB
/
cookie.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package networkutil
import (
"net/http"
"time"
)
type CookieOperation struct {
Path string
Domain string
Secure bool
HttpOnly bool
}
func NewCookieOp(domain string) *CookieOperation {
path := "/"
return &CookieOperation{
Path: path,
Domain: domain,
Secure: true,
HttpOnly: true,
}
}
// Set cookie.
//
// Arguments:
// w {http.ResponseWriter} - http writer.
// name {string} - cookie key.
// value {string} - cookie value.
// exp {int} - date of expiry. It is an hourly unit.
func (c *CookieOperation) Set(w http.ResponseWriter, name string, value string, exp int) {
expires := time.Now().Add(time.Duration(exp) * time.Hour)
maxAge := 60 * 60 * exp
cookie := &http.Cookie{
Name: name,
Value: value,
Expires: expires,
MaxAge: maxAge,
Secure: c.Secure,
Path: c.Path,
Domain: c.Domain,
HttpOnly: c.HttpOnly,
SameSite: http.SameSiteNoneMode,
}
http.SetCookie(w, cookie)
}
// Delete cookie
//
// Arguments:
// w {http.ResponseWriter} - http writer.
// req {http.Request} - http request.
// name {string} - cookie key.
func (c *CookieOperation) Delete(w http.ResponseWriter, req *http.Request, name string) error {
cookie, err := req.Cookie(name)
if err != nil {
return err
}
cookie.Expires = time.Unix(0, 0)
cookie.MaxAge = -1
cookie.Secure = c.Secure
cookie.Path = c.Path
cookie.Domain = c.Domain
cookie.HttpOnly = c.HttpOnly
cookie.SameSite = http.SameSiteNoneMode
http.SetCookie(w, cookie)
return nil
}
// Get cookie.
//
// Arguments:
// req {http.Request} - http request.
// name {string} - cookie key.
//
// Retruns:
// {string} - cookie value.
func (c *CookieOperation) Get(req *http.Request, name string) (string, error) {
cookie, err := req.Cookie(name)
if err != nil {
return "", err
}
return cookie.Value, nil
}