-
Notifications
You must be signed in to change notification settings - Fork 5
/
cookiejar.go
54 lines (46 loc) · 1.09 KB
/
cookiejar.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
package nscjar
import (
"io"
"net/http"
)
// CookieJar is a simple struct used to manage the cookies
type CookieJar struct {
cookies []*http.Cookie
}
// NewCookieJar function returns a newly initialized CookieJar struct
func NewCookieJar() *CookieJar {
return &CookieJar{make([]*http.Cookie, 0)}
}
// AddCookie method is used to add a cookie to the jar
func (j *CookieJar) AddCookie(c *http.Cookie) {
if c.Path == "" {
c.Path = "/"
}
if c == nil {
return
}
for i, val := range j.cookies {
if val.Domain == c.Domain && val.Path == c.Path && val.Name == c.Name {
j.cookies[i] = c
return
}
}
j.cookies = append(j.cookies, c)
}
// AddCookies method is used to add multiple cookies to the jar at once
func (j *CookieJar) AddCookies(c ...*http.Cookie) {
for _, val := range c {
j.AddCookie(val)
}
}
// Marshal method is used to write the cookie data in the passed io.Writer in netscape cookie data format
func (j CookieJar) Marshal(wr io.Writer) error {
p := Parser{}
for _, val := range j.cookies {
err := p.Marshal(wr, val)
if err != nil {
return err
}
}
return nil
}