-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcookie.go
More file actions
101 lines (83 loc) · 1.48 KB
/
cookie.go
File metadata and controls
101 lines (83 loc) · 1.48 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
96
97
98
99
100
101
package utils
import (
"net/http"
"strconv"
"time"
)
/*
cookie[0] => name string
cookie[1] => value string
cookie[2] => expires string
cookie[3] => path string
cookie[4] => domain string
cookie[5] => httpOnly bool
cookie[6] => secure bool
*/
func SetCookie(w http.ResponseWriter, target map[string]string, args ...interface{}) *http.Cookie {
if len(args) < 2 {
return nil
}
const LEN = 7
var cookie = [LEN]interface{}{}
for k, v := range args {
if k >= LEN {
break
}
cookie[k] = v
}
var (
name string
value string
expires int
path string
domain string
httpOnly bool
secure bool
)
if v, ok := cookie[0].(string); ok {
name = v
} else {
return nil
}
if v, ok := cookie[1].(string); ok {
value = v
} else {
return nil
}
if v, ok := cookie[2].(int); ok {
expires = v
}
if v, ok := cookie[3].(string); ok {
path = v
}
if v, ok := cookie[4].(string); ok {
domain = v
}
if v, ok := cookie[5].(bool); ok {
httpOnly = v
}
if v, ok := cookie[6].(bool); ok {
secure = v
}
pCookie := &http.Cookie{
Name: name,
Value: value,
Path: path,
Domain: domain,
HttpOnly: httpOnly,
Secure: secure,
}
if expires != 0 {
d, _ := time.ParseDuration(strconv.Itoa(expires) + "s")
pCookie.Expires = time.Now().Add(d)
if target != nil {
if expires > 0 {
target[pCookie.Name] = pCookie.Value
} else {
delete(target, pCookie.Name)
}
}
}
http.SetCookie(w, pCookie)
return pCookie
}