-
Notifications
You must be signed in to change notification settings - Fork 26
/
jar.go
102 lines (91 loc) · 1.95 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package requests
import (
"net/http/cookiejar"
"net/url"
"github.com/gospider007/gtls"
"golang.org/x/net/publicsuffix"
)
type Jar interface { // size=8
ClearCookies()
GetCookies(u *url.URL) Cookies
SetCookies(*url.URL, Cookies)
}
// 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
}
cooks, err := any2cookies(href, cookies...)
if err != nil {
return err
}
obj.option.Jar.SetCookies(href, cooks)
return nil
}
// 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
}
func any2cookies(u *url.URL, cookies ...any) (Cookies, error) {
domain := getDomain(u)
var result Cookies
for _, cookie := range cookies {
cooks, err := ReadCookies(cookie)
if err != nil {
return cooks, err
}
for _, cook := range cooks {
if cook.Path == "" {
cook.Path = "/"
}
if cook.Domain == "" {
cook.Domain = domain
}
}
result = append(result, cooks...)
}
return result, nil
}
// Set cookies
func (obj *jar) SetCookies(u *url.URL, cookies Cookies) {
obj.jar.SetCookies(u, cookies)
}
// Clear cookies
func (obj *jar) ClearCookies() {
jar, _ := cookiejar.New(nil)
obj.jar = jar
}