/
transport.go
88 lines (71 loc) · 1.81 KB
/
transport.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
package yarl
import (
"net"
"net/http"
"net/url"
"golang.org/x/net/proxy"
"github.com/pkg/errors"
)
// Transport sets a custom transport for the http client. If the transport is
// not a *http.Transport, no further customization can be done to the transport
func (req *Request) Transport(r http.RoundTripper) *Request {
if req.hasError() {
return req
}
req.client.Transport = r
return req
}
// UnixSocket sets the request to be sent to a unix socket.
func (req *Request) UnixSocket(path string) *Request {
if req.hasError() {
return req
}
transport, ok := req.client.Transport.(*http.Transport)
if !ok {
req.err = errors.Errorf("can't set dialer for custom transport")
}
if transport == nil {
transport = &http.Transport{}
req.client.Transport = transport
}
transport.Dial = func(_, _ string) (net.Conn, error) {
return net.Dial("unix", path)
}
return req
}
// Proxy sets the proxy used to perform the request. It supports http/https, and
// socks5 proxy.
func (req *Request) Proxy(proxyURL string) *Request {
if req.hasError() {
return req
}
transport, ok := req.client.Transport.(*http.Transport)
if !ok {
req.err = errors.Errorf("can't set proxy for custom transport")
}
if transport == nil {
transport = &http.Transport{}
req.client.Transport = transport
}
u, err := url.Parse(proxyURL)
if err != nil {
req.err = errors.Wrap(err, "parse proxy url")
return req
}
switch u.Scheme {
case "http":
transport.Proxy = http.ProxyURL(u)
case "https":
transport.Proxy = http.ProxyURL(u)
case "socks5":
dialer, err := proxy.SOCKS5("tcp", u.Host, nil, proxy.Direct)
if err != nil {
req.err = errors.Wrap(err, "create socks5 proxy")
return req
}
transport.Dial = dialer.Dial
default:
req.err = errors.Errorf("unsupported proxy scheme %s", u.Scheme)
}
return req
}