-
Notifications
You must be signed in to change notification settings - Fork 19
/
unix_transport.go
105 lines (88 loc) · 2.57 KB
/
unix_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package unix_transport
import (
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
func NewWithTLS(socketPath string, tlsConfig *tls.Config) *http.Transport {
unixTransport := &http.Transport{TLSClientConfig: tlsConfig}
unixTransport.RegisterProtocol("unix", NewUnixRoundTripperTls(socketPath, tlsConfig))
return unixTransport
}
func New(socketPath string) *http.Transport {
unixTransport := &http.Transport{}
unixTransport.RegisterProtocol("unix", NewUnixRoundTripper(socketPath))
return unixTransport
}
type UnixRoundTripper struct {
path string
conn httputil.ClientConn
useTls bool
tlsConfig *tls.Config
}
func NewUnixRoundTripper(path string) *UnixRoundTripper {
return &UnixRoundTripper{path: path}
}
func NewUnixRoundTripperTls(path string, tlsConfig *tls.Config) *UnixRoundTripper {
return &UnixRoundTripper{
path: path,
useTls: true,
tlsConfig: tlsConfig,
}
}
// The RoundTripper (http://golang.org/pkg/net/http/#RoundTripper) for the socket transport dials the socket
// each time a request is made.
func (roundTripper UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
var conn net.Conn
var err error
if roundTripper.useTls {
conn, err = tls.Dial("unix", roundTripper.path, roundTripper.tlsConfig)
if err != nil {
return nil, err
}
if conn == nil {
return nil, errors.New("net/http: Transport.DialTLS returned (nil, nil)")
}
if tc, ok := conn.(*tls.Conn); ok {
// Handshake here, in case DialTLS didn't. TLSNextProto below
// depends on it for knowing the connection state.
if err := tc.Handshake(); err != nil {
go conn.Close()
return nil, err
}
}
} else {
conn, err = net.Dial("unix", roundTripper.path)
if err != nil {
return nil, err
}
}
socketClientConn := httputil.NewClientConn(conn, nil)
defer socketClientConn.Close()
newReq, err := roundTripper.rewriteRequest(req)
if err != nil {
return nil, err
}
return socketClientConn.Do(newReq)
}
func (roundTripper *UnixRoundTripper) rewriteRequest(req *http.Request) (*http.Request, error) {
requestPath := req.URL.Path
if !strings.HasPrefix(requestPath, roundTripper.path) {
return nil, fmt.Errorf("Wrong unix socket [unix://%s]. Expected unix socket is [%s]", requestPath, roundTripper.path)
}
reqPath := strings.TrimPrefix(requestPath, roundTripper.path)
newReqUrl := fmt.Sprintf("unix://%s", reqPath)
var err error
newURL, err := url.Parse(newReqUrl)
if err != nil {
return nil, err
}
req.URL.Path = newURL.Path
req.URL.Host = roundTripper.path
return req, nil
}