-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxyManager.go
More file actions
80 lines (63 loc) · 1.32 KB
/
Copy pathproxyManager.go
File metadata and controls
80 lines (63 loc) · 1.32 KB
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
package main
import (
"log"
"net/http"
"net/url"
"time"
)
type ProxySource interface {
GetProxyList() ([]string, error)
}
type ProxyRequest interface {
Request(pm *ProxyManager) error
}
type ProxyManager struct {
proxyList []string
proxySource ProxySource
client *http.Client
}
func newProxyManager(proxySource ProxySource, timeout time.Duration) *ProxyManager {
pm := &ProxyManager{
proxySource: proxySource,
client: &http.Client{
Timeout: timeout,
},
}
return pm
}
func (pm *ProxyManager) getNextProxy() (string, error) {
length := len(pm.proxyList)
if length == 0 {
res, err := pm.proxySource.GetProxyList()
if err != nil {
return "", err
}
pm.proxyList = res
length = len(pm.proxyList)
}
lastElement := pm.proxyList[length-1]
pm.proxyList = pm.proxyList[:length-1]
return lastElement, nil
}
func (pm *ProxyManager) RotateProxy() error {
proxy, err := pm.getNextProxy()
if err != nil {
return err
}
proxyUrl, err := url.Parse(proxy)
if err != nil {
return err
}
log.Printf("Using proxy '%s'\n", proxy)
pm.client.CloseIdleConnections()
pm.client.Transport = &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
}
return nil
}
func (pm *ProxyManager) GetClient() *http.Client {
return pm.client
}
func (pm *ProxyManager) Do(pr ProxyRequest) error {
return pr.Request(pm)
}