-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpWorker.go
109 lines (94 loc) · 2.25 KB
/
httpWorker.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
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"sync"
"time"
"github.com/olehbozhok/freeproxyfinder/parsers"
)
type ProxyWorker struct {
wg sync.WaitGroup
mut sync.Mutex
i int
activeProxies []parsers.ProxySocks5Conf
}
func (pW *ProxyWorker) UpdateProxies() {
proxies, err := parsers.GetProxiesListSpysOne("*")
if err != nil {
log.Printf("error parsers.GetProxiesListSpysOne err:%v\n", err)
return
}
var activeProxies []parsers.ProxySocks5Conf
addActiveProxy := func(proxy parsers.ProxySocks5Conf) {
pW.mut.Lock()
activeProxies = append(activeProxies, proxy)
pW.mut.Unlock()
}
log.Printf("Got proxies %d\n", len(proxies))
log.Printf("Run proxies check\n")
wg := sync.WaitGroup{}
wg.Add(len(proxies))
for _, proxy := range proxies {
go func(pr parsers.ProxySocks5Conf) {
defer wg.Done()
latency, err := pr.CheckLatency()
if err != nil {
// log.Printf("error adress:%s err:%v\n", pr.Address, err)
return
}
if latency < 15.0 && err == nil {
pr.LastCheckLatency = time.Now()
addActiveProxy(pr)
}
}(proxy)
}
wg.Wait()
log.Printf("find %d active proxies\n", len(activeProxies))
pW.mut.Lock()
pW.activeProxies = activeProxies
pW.mut.Unlock()
}
func (pW *ProxyWorker) GetDialer() (parsers.Dialer, error) {
pW.mut.Lock()
defer pW.mut.Unlock()
if len(pW.activeProxies) != 0 {
n := pW.i % len(pW.activeProxies)
pc := &pW.activeProxies[n]
dialer, err := pc.GetDialer()
pW.i++
return dialer, err
}
return nil, errors.New("no active proxies")
}
func (pW *ProxyWorker) HttpHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
country := r.URL.Query().Get("country")
// copy slice
pW.mut.Lock()
activeProxies := pW.activeProxies
pW.mut.Unlock()
if country == "" {
data, err := json.Marshal(activeProxies)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
return
}
var filteredCountry []parsers.ProxySocks5Conf
for _, proxy := range activeProxies {
if proxy.CountryIsoCode == country {
filteredCountry = append(filteredCountry, proxy)
}
}
data, err := json.Marshal(filteredCountry)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
return
}