-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
93 lines (76 loc) · 2.19 KB
/
session.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
package gohttp
import (
"net/http"
"net/http/cookiejar"
"net/url"
"time"
"golang.org/x/net/publicsuffix"
)
var _ http.CookieJar = &Session{}
// Session provides cookie persistence and configuration.
type Session struct {
client *http.Client
Header http.Header
}
func newSession(client *http.Client) *Session {
return &Session{client, make(http.Header)}
}
// NewSession creates and initializes a new Session using initial contents.
func NewSession() *Session {
c := new(http.Client)
c.Jar, _ = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
return newSession(c)
}
func (s *Session) setProxy(fn func(*http.Request) (*url.URL, error)) {
var tr *http.Transport
var ok bool
if s.client.Transport == nil {
if tr, ok = http.DefaultTransport.(*http.Transport); ok {
tr.Proxy = fn
}
} else {
if tr, ok = s.client.Transport.(*http.Transport); ok {
tr.Proxy = fn
}
}
if !ok {
panic("Transport is not *http.Transport type")
}
}
// SetProxy sets Session client transport proxy.
func (s *Session) SetProxy(proxy string) error {
proxyURL, err := url.Parse(proxy)
if err != nil {
return err
}
s.setProxy(http.ProxyURL(proxyURL))
return nil
}
// SetNoProxy sets Session client use no proxy.
func (s *Session) SetNoProxy() {
s.setProxy(nil)
}
// SetProxyFromEnvironment sets Session client use environment proxy.
func (s *Session) SetProxyFromEnvironment() {
s.setProxy(http.ProxyFromEnvironment)
}
// SetTimeout sets Session client timeout. Zero means no timeout.
func (s *Session) SetTimeout(d time.Duration) {
s.client.Timeout = d
}
// SetClient sets default client.
func (s *Session) SetClient(c *http.Client) {
s.client = c
}
// Cookies returns the cookies to send in a request for the given URL.
func (s *Session) Cookies(u *url.URL) []*http.Cookie {
return s.client.Jar.Cookies(u)
}
// SetCookie handles the receipt of the cookie in a reply for the given URL.
func (s *Session) SetCookie(u *url.URL, name, value string) {
s.SetCookies(u, []*http.Cookie{{Name: name, Value: value}})
}
// SetCookies handles the receipt of the cookies in a reply for the given URL.
func (s *Session) SetCookies(u *url.URL, cookies []*http.Cookie) {
s.client.Jar.SetCookies(u, cookies)
}