-
Notifications
You must be signed in to change notification settings - Fork 104
/
Proxy.go
104 lines (93 loc) · 1.86 KB
/
Proxy.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
package main
import (
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/btccom/connectproxy"
"golang.org/x/net/proxy"
)
type Dialer interface {
// Dial connects to the given address.
Dial(network, addr string) (net.Conn, error)
}
func GetProxyURLFromEnv() (url string) {
url = os.Getenv("ALL_PROXY")
if len(url) < 1 {
url = os.Getenv("all_proxy")
}
if len(url) < 1 {
url = os.Getenv("HTTPS_PROXY")
}
if len(url) < 1 {
url = os.Getenv("https_proxy")
}
if len(url) < 1 {
url = os.Getenv("HTTP_PROXY")
}
if len(url) < 1 {
url = os.Getenv("http_proxy")
}
return
}
func RegularProxyURL(url string) string {
if len(url) < 1 {
return url
}
url = strings.TrimSpace(url)
pos := strings.Index(url, "://")
var protocol, address string
if pos < 0 {
protocol = "http"
address = url
} else {
protocol = strings.ToLower(url[:pos])
address = url[pos+3:]
}
switch protocol {
case "":
protocol = "http"
case "socks4":
fallthrough
case "socks4a":
fallthrough
case "socks5":
protocol = "socks"
}
return fmt.Sprintf("%s://%s", protocol, address)
}
func GetProxyDialer(proxyURL string, timeout time.Duration, insecureSkipVerify bool) (dailer Dialer, err error) {
proxyURL = RegularProxyURL(proxyURL)
u, err := url.Parse(proxyURL)
if err != nil {
return
}
if u.Scheme == "socks" {
var auth proxy.Auth
auth.User = u.User.Username()
auth.Password, _ = u.User.Password()
dailer, err = proxy.SOCKS5("tcp", u.Host, &auth, &net.Dialer{
Timeout: timeout,
})
return
}
if u.Scheme == "http" || u.Scheme == "https" {
dailer, err = connectproxy.NewWithConfig(
u,
&net.Dialer{
Timeout: timeout,
},
&connectproxy.Config{
InsecureSkipVerify: insecureSkipVerify,
DialTimeout: timeout,
},
)
return
}
if len(proxyURL) > 0 {
err = fmt.Errorf("unknown proxy scheme '%s'", u.Scheme)
}
return
}