Skip to content

Commit ab29d8e

Browse files
committed
first commit
0 parents  commit ab29d8e

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/deprecated/proxyhandler
2+
3+
go 1.14

proxyhandler.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package proxyhandler
2+
3+
import (
4+
"os"
5+
"bufio"
6+
"errors"
7+
"sync"
8+
"math/rand"
9+
)
10+
11+
// ProxyHandler defines the handler struct
12+
type ProxyHandler struct {
13+
Path string
14+
Proxies []string
15+
Mux sync.Mutex
16+
}
17+
18+
// Create creates a new ProxyHandler
19+
func Create(path string) (*ProxyHandler, error) {
20+
handler := &ProxyHandler{Path: path, Proxies: []string{}}
21+
22+
return handler, nil
23+
}
24+
25+
// Init initializes the ProxyHandler
26+
func (h *ProxyHandler) Init() error {
27+
file, err := os.Open(h.Path)
28+
if err != nil {
29+
return err
30+
}
31+
defer file.Close()
32+
33+
scanner := bufio.NewScanner(file)
34+
35+
for scanner.Scan() {
36+
h.Proxies = append(h.Proxies, scanner.Text())
37+
}
38+
39+
return nil
40+
}
41+
42+
// SmartRotateProxy returns the next proxy in the list and appends the old one to the end of the list
43+
func (h *ProxyHandler) SmartRotateProxy() (string, error) {
44+
if (len(h.Proxies) == 0) {
45+
return "", errors.New("No Proxies loaded")
46+
}
47+
48+
var p string
49+
h.Mux.Lock()
50+
p, h.Proxies = h.Proxies[0], h.Proxies[1:]
51+
h.Proxies = append(h.Proxies, p)
52+
h.Mux.Unlock()
53+
54+
return p, nil
55+
}
56+
57+
// RandomProxy returns a random proxy from the list
58+
func (h *ProxyHandler) RandomProxy() (string, error) {
59+
if (len(h.Proxies) == 0) {
60+
return "", errors.New("No Proxies loaded")
61+
}
62+
63+
i := rand.Intn(len(h.Proxies))
64+
p := h.Proxies[i]
65+
66+
return p, nil
67+
}
68+

0 commit comments

Comments
 (0)