-
Notifications
You must be signed in to change notification settings - Fork 2
/
http_proxy.go
122 lines (101 loc) · 2.45 KB
/
http_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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package gotiktoklive
// Copied from: https://gist.github.com/jim3ma/3750675f141669ac4702bc9deaf31c6b
import (
"bufio"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"golang.org/x/net/proxy"
)
type direct struct{}
// Direct is a direct proxy: one that makes network connections directly.
var Direct = direct{}
func (direct) Dial(network, addr string) (net.Conn, error) {
return net.Dial(network, addr)
}
// httpsDialer
type httpsDialer struct{}
// HTTPSDialer is a https proxy: one that makes network connections on tls.
var HttpsDialer = httpsDialer{}
var TlsConfig = &tls.Config{}
func (d httpsDialer) Dial(network, addr string) (c net.Conn, err error) {
c, err = tls.Dial("tcp", addr, TlsConfig)
if err != nil {
fmt.Println(err)
}
return
}
// httpProxy is a HTTP/HTTPS connect proxy.
type httpProxy struct {
host string
haveAuth bool
username string
password string
forward proxy.Dialer
}
func newHTTPProxy(uri *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
s := new(httpProxy)
s.host = uri.Host
s.forward = forward
if uri.User != nil {
s.haveAuth = true
s.username = uri.User.Username()
s.password, _ = uri.User.Password()
}
return s, nil
}
func (s *httpProxy) Dial(network, addr string) (net.Conn, error) {
// Dial and create the https client connection.
c, err := s.forward.Dial("tcp", s.host)
if err != nil {
return nil, err
}
// HACK. http.ReadRequest also does this.
reqURL, err := url.Parse("http://" + addr)
if err != nil {
c.Close()
return nil, err
}
reqURL.Scheme = ""
req, err := http.NewRequest("CONNECT", reqURL.String(), nil)
if err != nil {
c.Close()
return nil, err
}
req.Close = false
if s.haveAuth {
req.SetBasicAuth(s.username, s.password)
}
// req.Header.Set("User-Agent", "Powerby Gota")
err = req.Write(c)
if err != nil {
c.Close()
return nil, err
}
resp, err := http.ReadResponse(bufio.NewReader(c), req)
if err != nil {
// TODO close resp body ?
resp.Body.Close()
c.Close()
return nil, err
}
resp.Body.Close()
if resp.StatusCode != 200 {
c.Close()
err = fmt.Errorf("Connect server using proxy error, StatusCode [%d]", resp.StatusCode)
return nil, err
}
return c, nil
}
func FromURL(u *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
return proxy.FromURL(u, forward)
}
func FromEnvironment() proxy.Dialer {
return proxy.FromEnvironment()
}
func init() {
proxy.RegisterDialerType("http", newHTTPProxy)
proxy.RegisterDialerType("https", newHTTPProxy)
}