forked from h2non/gock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
responder.go
105 lines (91 loc) · 2.51 KB
/
responder.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 gock
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
)
// Responder builds a mock http.Response based on the given Response mock.
func Responder(req *http.Request, mock *Response, res *http.Response) (*http.Response, error) {
// If error present, reply it
err := mock.Error
if err != nil {
return nil, err
}
if res == nil {
res = createResponse(req)
}
// Apply response filter
for _, filter := range mock.Filters {
if !filter(res) {
return res, nil
}
}
// Define mock status code
if mock.StatusCode != 0 {
res.Status = strconv.Itoa(mock.StatusCode) + " " + http.StatusText(mock.StatusCode)
res.StatusCode = mock.StatusCode
}
// Define headers by merging fields
res.Header = mergeHeaders(res, mock)
// Define mock body, if present
if len(mock.BodyBuffer) > 0 {
res.ContentLength = int64(len(mock.BodyBuffer))
res.Body = createReadCloser(mock.BodyBuffer)
}
// Apply response mappers
for _, mapper := range mock.Mappers {
if tres := mapper(res); tres != nil {
res = tres
}
}
// Sleep to simulate delay, if necessary
if mock.ResponseDelay > 0 {
// allow escaping from sleep due to request context expiration or cancellation
t := time.NewTimer(mock.ResponseDelay)
select {
case <-t.C:
case <-req.Context().Done():
// cleanly stop the timer
if !t.Stop() {
<-t.C
}
}
}
// check if the request context has ended. we could put this up in the delay code above, but putting it here
// has the added benefit of working even when there is no delay (very small timeouts, already-done contexts, etc.)
if err = req.Context().Err(); err != nil {
// cleanly close the response and return the context error
io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
return nil, err
}
return res, err
}
// createResponse creates a new http.Response with default fields.
func createResponse(req *http.Request) *http.Response {
return &http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
Proto: "HTTP/1.1",
Request: req,
Header: make(http.Header),
Body: createReadCloser([]byte{}),
}
}
// mergeHeaders copies the mock headers.
func mergeHeaders(res *http.Response, mres *Response) http.Header {
for key, values := range mres.Header {
for _, value := range values {
res.Header.Add(key, value)
}
}
return res.Header
}
// createReadCloser creates an io.ReadCloser from a byte slice that is suitable for use as an
// http response body.
func createReadCloser(body []byte) io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader(body))
}