forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_transport.go
57 lines (45 loc) · 1.15 KB
/
handler_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
package client
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
)
// See "Handler" client option.
type handlerTransport struct {
handler http.Handler
}
// RoundTrip completes the http.RoundTripper interface.
// It can be used to test calls to a server's handler.
func (t *handlerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
reqCopy := *req
if reqCopy.Proto == "" {
reqCopy.Proto = fmt.Sprintf("HTTP/%d.%d", reqCopy.ProtoMajor, reqCopy.ProtoMinor)
}
if reqCopy.Body != nil {
if reqCopy.ContentLength == -1 {
reqCopy.TransferEncoding = []string{"chunked"}
}
} else {
reqCopy.Body = io.NopCloser(bytes.NewReader(nil))
}
if reqCopy.RequestURI == "" {
reqCopy.RequestURI = reqCopy.URL.RequestURI()
}
recorder := httptest.NewRecorder()
t.handler.ServeHTTP(recorder, &reqCopy)
resp := http.Response{
Request: &reqCopy,
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 = io.NopCloser(recorder.Body)
}
return &resp, nil
}