forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpmock.go
311 lines (274 loc) · 6.61 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package testutil
import (
"encoding/json"
"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)
}
)
// NewHttpRequest for http testing, alias of NewHTTPRequest()
//
// Deprecated: use NewHTTPRequest() instead.
func NewHttpRequest(method, path string, data *MD) *http.Request {
return NewHTTPRequest(method, path, data)
}
// NewHTTPRequest quick create request for http testing
// Usage:
//
// req := NewHttpRequest("GET", "/path", nil)
//
// // with data 1
// body := strings.NewReader("string ...")
// req := NewHttpRequest("POST", "/path", &MD{
// Body: body,
// Headers: M{"x-head": "val"}
// })
//
// // with data 2
// req := NewHttpRequest("POST", "/path", &MD{
// BodyString: "data string",
// Headers: M{"x-head": "val"}
// })
func NewHTTPRequest(method, path string, data *MD) *http.Request {
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 {
for k, v := range data.Headers {
req.Header.Set(k, v)
}
}
if data.BeforeSend != nil {
data.BeforeSend(req)
}
}
return req
}
// 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,
// HeaderM: M{"x-head": "val"}
// })
//
// // with data 2
// res := MockRequest(handler, "POST", "/path", &MD{
// BodyString: "data string",
// HeaderM: M{"x-head": "val"}
// })
func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder {
// w.Result() will return http.Response
w := httptest.NewRecorder()
r := NewHTTPRequest(method, path, data)
// s := httptest.NewServer()
h.ServeHTTP(w, r)
return w
}
// EchoReply http response data reply model
type EchoReply struct {
Origin string `json:"origin"`
URL string `json:"url"`
Method string `json:"method"`
// Query data
Query map[string]any `json:"query,omitempty"`
Headers map[string]any `json:"headers,omitempty"`
Form map[string]any `json:"form,omitempty"`
// Body data string
Body string `json:"body,omitempty"`
JSON any `json:"json,omitempty"`
Files map[string]any `json:"files,omitempty"`
}
// ContentType get content type
func (r *EchoReply) ContentType() string {
return r.Headers["Content-Type"].(string)
}
// EchoServer for testing http request.
type EchoServer struct {
*httptest.Server
}
// HostAddr get host address. eg: 127.0.0.1:8999
func (s *EchoServer) HostAddr() string {
return s.Listener.Addr().String()
}
// HTTPHost get http host address. eg: http://127.0.0.1:8999
func (s *EchoServer) HTTPHost() string {
return "http://" + s.HostAddr()
}
// NewEchoServer create an echo server for testing.
//
// Usage on testing:
//
// var testSrvAddr string
//
// func TestMain(m *testing.M) {
// // create server
// s := testutil.NewEchoServer()
// defer s.Close()
// testSrvAddr = s.HTTPHost()
// fmt.Println("Test server listen on:", testSrvAddr)
//
// m.Run()
// }
//
// // in a test case ...
// res := http.Get(testSrvAddr)
// rpl := testutil.ParseRespToReply(res)
// // assert ...
func NewEchoServer() *EchoServer {
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Server", "goutil/echo-server")
w.WriteHeader(http.StatusOK)
// w.Header().Set("Connection", "close")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
err := enc.Encode(BuildEchoReply(r))
if err != nil {
_, _ = w.Write([]byte(`{"error": "encode error"}`))
}
}))
return &EchoServer{
Server: hs,
}
}
// BuildEchoReply build reply body data
func BuildEchoReply(r *http.Request) *EchoReply {
// get headers
headers := stringsMapToAnyMap(r.Header)
// get query args
args := stringsMapToAnyMap(r.URL.Query())
cType := r.Header.Get("Content-Type")
method := strings.ToUpper(r.Method)
var jsonBody any
var bodyStr string
var form, files map[string]any
if method == "POST" || method == "PUT" || method == "PATCH" {
// get form data
_ = r.ParseForm()
form = stringsMapToAnyMap(r.PostForm)
// get form files
if r.MultipartForm != nil {
files = make(map[string]any)
for k, fhs := range r.MultipartForm.File {
if len(fhs) == 1 {
files[k] = fhs[0]
} else {
files[k] = fhs
}
}
}
// get body data
if len(r.PostForm) > 0 {
bodyStr = r.PostForm.Encode()
} else if r.Body != nil {
// defer r.Body.Close()
body, _ := io.ReadAll(r.Body)
bodyStr = string(body)
// try to parse json
if len(body) > 0 && strings.HasPrefix(cType, "application/json") {
_ = json.Unmarshal(body, &jsonBody)
}
}
}
return &EchoReply{
URL: r.URL.String(),
Origin: r.RemoteAddr,
Method: method,
Body: bodyStr,
JSON: jsonBody,
Query: args,
Form: form,
Files: files,
Headers: headers,
}
}
/*
// HTTP tool for testing
var HTTP = &HTTPTool{}
// HTTPTool http tool for testing
type HTTPTool struct {
}
func (ht *HTTPTool) ParseRespToReply(r *http.Response) *EchoReply {
return ParseRespToReply(r)
}
func (ht *HTTPTool) ParseBodyToReply(bd io.ReadCloser) *EchoReply {
return ParseBodyToReply(bd)
}
*/
// ParseRespToReply parse http response to reply
func ParseRespToReply(w *http.Response) *EchoReply {
if w.Body == nil {
return &EchoReply{}
}
if w.Request != nil && w.Request.Method == "HEAD" {
req := w.Request
rpl := &EchoReply{
URL: req.URL.String(),
Method: req.Method,
Headers: stringsMapToAnyMap(req.Header),
}
return rpl
}
return ParseBodyToReply(w.Body)
}
// ParseBodyToReply parse http body to reply
func ParseBodyToReply(bd io.ReadCloser) *EchoReply {
rpl := &EchoReply{}
if bd == nil {
return rpl
}
err := json.NewDecoder(bd).Decode(rpl)
if err != nil {
panic(err)
}
return rpl
}
func stringsMapToAnyMap(ssMp map[string][]string) map[string]any {
if len(ssMp) == 0 {
return nil
}
anyMp := make(map[string]any, len(ssMp))
for k, v := range ssMp {
if len(v) == 1 {
anyMp[k] = v[0]
continue
}
anyMp[k] = v
}
return anyMp
}