-
Notifications
You must be signed in to change notification settings - Fork 185
/
httpmock.go
77 lines (70 loc) · 1.59 KB
/
httpmock.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
package testutil
import (
"io"
"net/http"
"net/http/httptest"
"strings"
)
// some data.
type (
// M short name for map
M map[string]string
// MD simple request data
MD struct {
// Headers headers
Headers M
// Body body. eg: strings.NewReader("name=inhere")
Body io.Reader
// BodyString quick add body.
BodyString string
// BeforeSend callback
BeforeSend func(req *http.Request)
}
)
// MockRequest mock an HTTP Request
// Usage:
// handler := router.New()
// res := MockRequest(handler, "GET", "/path", nil)
// // with data 1
// body := strings.NewReader("string ...")
// res := MockRequest(handler, "POST", "/path", &MD{
// Body: body,
// Headers: M{"x-head": "val"}
// })
// // with data 2
// res := MockRequest(handler, "POST", "/path", &MD{
// BodyString: "data string",
// Headers: M{"x-head": "val"}
// })
func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder {
var body io.Reader
if data != nil {
if data.Body != nil {
body = data.Body
} else if data.BodyString != "" {
body = strings.NewReader(data.BodyString)
}
}
// create fake request
req, err := http.NewRequest(method, path, body)
if err != nil {
panic(err)
}
req.RequestURI = req.URL.String()
if data != nil {
if len(data.Headers) > 0 {
// req.Header.Set("Content-Type", "text/plain")
for k, v := range data.Headers {
req.Header.Set(k, v)
}
}
if data.BeforeSend != nil {
data.BeforeSend(req)
}
}
// w.Result() will return http.Response
w := httptest.NewRecorder()
// s := httptest.NewServer()
h.ServeHTTP(w, req)
return w
}