forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 3
/
binder.go
105 lines (85 loc) · 2.16 KB
/
binder.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 httpexpect
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
)
// Binder implements networkless http.RoundTripper attached directly to
// http.Handler.
//
// Binder emulates network communication by invoking given http.Handler
// directly. It passes httptest.ResponseRecorder as http.ResponseWriter
// to the handler, and then constructs http.Response from recorded data.
type Binder struct {
// HTTP handler invoked for every request.
Handler http.Handler
// TLS connection state used for https:// requests.
TLS *tls.ConnectionState
}
// NewBinder returns a new Binder given a http.Handler.
//
// Example:
//
// client := &http.Client{
// Transport: NewBinder(handler),
// }
func NewBinder(handler http.Handler) Binder {
return Binder{Handler: handler}
}
// RoundTrip implements http.RoundTripper.RoundTrip.
func (binder Binder) RoundTrip(origReq *http.Request) (*http.Response, error) {
req := *origReq
if req.Proto == "" {
req.Proto = fmt.Sprintf("HTTP/%d.%d", req.ProtoMajor, req.ProtoMinor)
}
if req.Body != nil && req.Body != http.NoBody {
if req.ContentLength == -1 {
req.TransferEncoding = []string{"chunked"}
}
} else {
req.Body = http.NoBody
}
if req.URL != nil && req.URL.Scheme == "https" && binder.TLS != nil {
req.TLS = binder.TLS
}
if req.RequestURI == "" {
req.RequestURI = req.URL.RequestURI()
}
recorder := httptest.NewRecorder()
binder.Handler.ServeHTTP(recorder, &req)
resp := http.Response{
Request: &req,
StatusCode: recorder.Code,
Status: http.StatusText(recorder.Code),
Header: recorder.Result().Header,
}
if recorder.Flushed {
resp.TransferEncoding = []string{"chunked"}
}
if recorder.Body != nil {
resp.Body = ioutil.NopCloser(recorder.Body)
}
return &resp, nil
}
type connNonTLS struct {
net.Conn
}
func (connNonTLS) RemoteAddr() net.Addr {
return &net.TCPAddr{IP: net.IPv4zero}
}
func (connNonTLS) LocalAddr() net.Addr {
return &net.TCPAddr{IP: net.IPv4zero}
}
type connTLS struct {
connNonTLS
state *tls.ConnectionState
}
func (c connTLS) Handshake() error {
return nil
}
func (c connTLS) ConnectionState() tls.ConnectionState {
return *c.state
}