-
Notifications
You must be signed in to change notification settings - Fork 13
/
cookie.go
71 lines (59 loc) · 1.57 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
package fasthttpsession
import (
"github.com/valyala/fasthttp"
"time"
)
func NewCookie() *Cookie {
return &Cookie{}
}
type Cookie struct {
}
// get cookie by name
func (c *Cookie) Get(ctx *fasthttp.RequestCtx, name string) (value string) {
cookieByte := ctx.Request.Header.Cookie(name)
if len(cookieByte) > 0 {
value = string(cookieByte)
}
return
}
// response set cookie
func (c *Cookie) Set(ctx *fasthttp.RequestCtx, name string, value string, domain string, expires time.Duration, secure bool) {
cookie := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(cookie)
cookie.SetKey(name)
cookie.SetPath("/")
cookie.SetHTTPOnly(true)
cookie.SetDomain(domain)
if expires >= 0 {
if expires == 0 {
// = 0 unlimited life
cookie.SetExpire(fasthttp.CookieExpireUnlimited)
} else {
// > 0
cookie.SetExpire(time.Now().Add(expires))
}
}
if ctx.IsTLS() && secure {
cookie.SetSecure(true)
}
cookie.SetValue(value)
ctx.Response.Header.SetCookie(cookie)
}
// delete cookie by cookie name
func (c *Cookie) Delete(ctx *fasthttp.RequestCtx, name string) {
// delete response cookie
ctx.Response.Header.DelCookie(name)
// reset response cookie
cookie := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(cookie)
cookie.SetKey(name)
cookie.SetValue("")
cookie.SetPath("/")
cookie.SetHTTPOnly(true)
//RFC says 1 second, but let's do it 1 minute to make sure is working...
exp := time.Now().Add(-time.Duration(1) * time.Minute)
cookie.SetExpire(exp)
ctx.Response.Header.SetCookie(cookie)
// delete request's cookie also
ctx.Request.Header.DelCookie(name)
}