-
Notifications
You must be signed in to change notification settings - Fork 6
/
cookie.go
108 lines (85 loc) · 1.62 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package fetch
import "strings"
type cookie struct {
data []cookieItem
}
type cookieItem struct {
Key string
Value string
}
func newCookie(origin ...string) *cookie {
c := &cookie{}
if len(origin) > 0 {
if origin[0] != "" {
c.Parse(origin[0])
}
}
return c
}
func (c *cookie) Parse(str string) (err error) {
str = strings.TrimSpace(str)
str = strings.TrimSuffix(str, ";")
str = strings.TrimSpace(str)
items := strings.Split(str, ";")
for _, item := range items {
item = strings.TrimSpace(item)
if item == "" {
continue
}
kv := strings.Split(item, "=")
if len(kv) != 2 {
continue
}
if err := c.Add(kv[0], kv[1]); err != nil {
return err
}
}
return
}
func (c *cookie) Add(key, value string) (err error) {
if key == "" {
return ErrCookieEmptyKey
}
c.data = append(c.data, cookieItem{key, value})
return nil
}
func (c *cookie) Get(key string) string {
for _, item := range c.data {
if item.Key == key {
return item.Value
}
}
return ""
}
func (c *cookie) Set(key, value string) (err error) {
for i, item := range c.data {
if item.Key == key {
c.data[i].Value = value
return nil
}
}
return c.Add(key, value)
}
func (c *cookie) Remove(key string) (err error) {
for i, item := range c.data {
if item.Key == key {
c.data = append(c.data[:i], c.data[i+1:]...)
return
}
}
return
}
func (c *cookie) Clear() error {
c.data = nil
return nil
}
func (c *cookie) Items() []cookieItem {
return c.data
}
func (c *cookie) String() string {
var ss []string
for _, item := range c.data {
ss = append(ss, item.Key+"="+item.Value)
}
return strings.Join(ss, "; ")
}