forked from gramework/gramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcookie.go
More file actions
95 lines (84 loc) · 2.21 KB
/
cookie.go
File metadata and controls
95 lines (84 loc) · 2.21 KB
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
94
95
// Copyright 2017-present Kirill Danshin and Gramework contributors
// Copyright 2019-present Highload LTD (UK CN: 11893420)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
package gramework
import (
"time"
"github.com/valyala/fasthttp"
)
const defaultCookiePath = "/"
// GetCookieDomain returns previously configured cookie domain and if cookie domain
// was configured at all
func (ctx *Context) GetCookieDomain() (domain string, wasConfigured bool) {
return ctx.App.cookieDomain, len(ctx.App.cookieDomain) > 0
}
func (ctx *Context) saveCookies() {
ctx.Cookies.Mu.Lock()
for k, v := range ctx.Cookies.Storage {
c := fasthttp.AcquireCookie()
c.SetKey(k)
c.SetValue(v)
if len(ctx.App.cookieDomain) > 0 {
c.SetDomain(ctx.App.cookieDomain)
}
if len(ctx.App.cookiePath) > 0 {
c.SetPath(ctx.App.cookiePath)
}
c.SetExpire(time.Now().Add(ctx.App.cookieExpire))
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
}