-
Notifications
You must be signed in to change notification settings - Fork 18
/
jar.go
87 lines (77 loc) · 1.61 KB
/
jar.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
package requests
import (
"net/http/cookiejar"
"net/url"
"github.com/gospider007/gtls"
"golang.org/x/net/publicsuffix"
)
// cookies jar
type Jar struct {
jar *cookiejar.Jar
}
// new cookies jar
func NewJar() *Jar {
j, _ := cookiejar.New(nil)
return &Jar{
jar: j,
}
}
// get cookies
func (obj *Client) GetCookies(href *url.URL) Cookies {
if obj.option.Jar == nil {
return nil
}
return obj.option.Jar.GetCookies(href)
}
// set cookies
func (obj *Client) SetCookies(href *url.URL, cookies ...any) error {
if obj.option.Jar == nil {
return nil
}
return obj.option.Jar.SetCookies(href, cookies...)
}
// clear cookies
func (obj *Client) ClearCookies() {
if obj.option.Jar == nil {
return
}
obj.option.Jar.ClearCookies()
}
// Get cookies
func (obj *Jar) GetCookies(u *url.URL) Cookies {
return obj.jar.Cookies(u)
}
func getDomain(u *url.URL) string {
domain := u.Hostname()
if _, addType := gtls.ParseHost(domain); addType == 0 {
if tlp, err := publicsuffix.EffectiveTLDPlusOne(domain); err == nil {
domain = tlp
}
}
return domain
}
// Set cookies
func (obj *Jar) SetCookies(u *url.URL, cookies ...any) error {
domain := getDomain(u)
for _, cookie := range cookies {
cooks, err := ReadCookies(cookie)
if err != nil {
return err
}
for _, cook := range cooks {
if cook.Path == "" {
cook.Path = "/"
}
if cook.Domain == "" {
cook.Domain = domain
}
}
obj.jar.SetCookies(u, cooks)
}
return nil
}
// Clear cookies
func (obj *Jar) ClearCookies() {
jar, _ := cookiejar.New(nil)
obj.jar = jar
}