forked from gramework/gramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.go
68 lines (61 loc) · 1.38 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
package gramework
import (
"github.com/valyala/fasthttp"
)
func (ctx *Context) saveCookies() {
ctx.Cookies.Mu.Lock()
for k, v := range ctx.Cookies.Storage {
c := fasthttp.AcquireCookie()
c.SetKey(k)
c.SetValue(v)
ctx.Response.Header.SetCookie(c)
fasthttp.ReleaseCookie(c)
}
ctx.Cookies.Mu.Unlock()
}
func (ctx *Context) loadCookies() {
ctx.Cookies.Storage = make(map[string]string, zero)
ctx.Request.Header.VisitAllCookie(ctx.loadCookieVisitor)
}
func (ctx *Context) loadCookieVisitor(k, v []byte) {
ctx.Cookies.Set(string(k), string(v))
}
// Set a cookie with given key to the value
func (c *Cookies) Set(key, value string) {
c.Mu.Lock()
if c.Storage == nil {
c.Storage = make(map[string]string, zero)
}
c.Storage[key] = value
c.Mu.Unlock()
}
// Get a cookie by given key
func (c *Cookies) Get(key string) (string, bool) {
c.Mu.Lock()
if c.Storage == nil {
c.Storage = make(map[string]string, zero)
c.Mu.Unlock()
return emptyString, false
}
if v, ok := c.Storage[key]; ok {
c.Mu.Unlock()
return v, ok
}
c.Mu.Unlock()
return emptyString, false
}
// Exists reports if the given key exists for current request
func (c *Cookies) Exists(key string) bool {
c.Mu.Lock()
if c.Storage == nil {
c.Storage = make(map[string]string, zero)
c.Mu.Unlock()
return false
}
if _, ok := c.Storage[key]; ok {
c.Mu.Unlock()
return ok
}
c.Mu.Unlock()
return false
}