github.com/gospider007/requests@v0.0.0-20240506025355-c73d46169a23/jar.go (about) 1 package requests 2 3 import ( 4 "net/http/cookiejar" 5 "net/url" 6 7 "github.com/gospider007/gtls" 8 "golang.org/x/net/publicsuffix" 9 ) 10 11 // cookies jar 12 type Jar struct { 13 jar *cookiejar.Jar 14 } 15 16 // new cookies jar 17 func NewJar() *Jar { 18 j, _ := cookiejar.New(nil) 19 return &Jar{ 20 jar: j, 21 } 22 } 23 24 // get cookies 25 func (obj *Client) GetCookies(href *url.URL) Cookies { 26 if obj.option.Jar == nil { 27 return nil 28 } 29 return obj.option.Jar.GetCookies(href) 30 } 31 32 // set cookies 33 func (obj *Client) SetCookies(href *url.URL, cookies ...any) error { 34 if obj.option.Jar == nil { 35 return nil 36 } 37 return obj.option.Jar.SetCookies(href, cookies...) 38 } 39 40 // clear cookies 41 func (obj *Client) ClearCookies() { 42 if obj.option.Jar == nil { 43 return 44 } 45 obj.option.Jar.ClearCookies() 46 } 47 48 // Get cookies 49 func (obj *Jar) GetCookies(u *url.URL) Cookies { 50 return obj.jar.Cookies(u) 51 } 52 func getDomain(u *url.URL) string { 53 domain := u.Hostname() 54 if _, addType := gtls.ParseHost(domain); addType == 0 { 55 if tlp, err := publicsuffix.EffectiveTLDPlusOne(domain); err == nil { 56 domain = tlp 57 } 58 } 59 return domain 60 } 61 62 // Set cookies 63 func (obj *Jar) SetCookies(u *url.URL, cookies ...any) error { 64 domain := getDomain(u) 65 for _, cookie := range cookies { 66 cooks, err := ReadCookies(cookie) 67 if err != nil { 68 return err 69 } 70 for _, cook := range cooks { 71 if cook.Path == "" { 72 cook.Path = "/" 73 } 74 if cook.Domain == "" { 75 cook.Domain = domain 76 } 77 } 78 obj.jar.SetCookies(u, cooks) 79 } 80 return nil 81 } 82 83 // Clear cookies 84 func (obj *Jar) ClearCookies() { 85 jar, _ := cookiejar.New(nil) 86 obj.jar = jar 87 }