-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
348 lines (286 loc) · 8.23 KB
/
request.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package request
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"go.nhat.io/httpmock/matcher"
"go.nhat.io/httpmock/must"
"go.nhat.io/httpmock/value"
)
// Request is an expectation.
//
// Deprecated: the package will be removed in the future.
type Request struct {
locker sync.Locker
// method is the expected HTTP method of the given request.
method string
// requestURI is the expected HTTP request URI of the given request.
// The uri does not need to be exactly same but satisfies the matcher.
requestURI matcher.Matcher
// requestHeader is a list of expected headers of the given request.
requestHeader matcher.HeaderMatcher
// requestBody is the expected body of the given request.
requestBody *matcher.BodyMatcher
// responseCode is the response code when the request is handled.
responseCode int
// responseHeader is a list of response headers to be sent to client when the request is handled.
responseHeader Header
run func(r *http.Request) ([]byte, error)
// The number of times to return the return arguments when setting
// expectations. 0 means to always return the value.
repeatability int
// Amount of times this request has been executed.
totalCalls int
// Holds a channel that will be used to block the Do until it either
// receives a message or is closed. nil means it returns immediately.
waitFor <-chan time.Time
waitTime time.Duration
}
// NewRequest creates a new request expectation.
func NewRequest(locker sync.Locker, method string, requestURI any) *Request {
return &Request{
locker: locker,
method: method,
responseCode: http.StatusOK,
requestURI: matcher.Match(requestURI),
repeatability: 0,
waitFor: nil,
run: func(r *http.Request) ([]byte, error) {
return nil, nil
},
}
}
func (r *Request) lock() {
r.locker.Lock()
}
func (r *Request) unlock() {
r.locker.Unlock()
}
// WithHeader sets an expected header of the given request.
//
// Server.Expect(httpmock.MethodGet, "/path").
// WithHeader("foo", "bar")
//
//nolint:unparam
func (r *Request) WithHeader(header string, value any) *Request {
r.lock()
defer r.unlock()
if r.requestHeader == nil {
r.requestHeader = matcher.HeaderMatcher{}
}
r.requestHeader[header] = matcher.Match(value)
return r
}
// WithHeaders sets a list of expected headers of the given request.
//
// Server.Expect(httpmock.MethodGet, "/path").
// WithHeaders(map[string]any{"foo": "bar"})
func (r *Request) WithHeaders(headers map[string]any) *Request {
for header, value := range headers {
r.WithHeader(header, value)
}
return r
}
// WithBody sets the expected body of the given request. It could be []byte, string, fmt.Stringer, or a Matcher.
//
// Server.Expect(httpmock.MethodGet, "/path").
// WithBody("hello world!")
func (r *Request) WithBody(body any) *Request {
r.lock()
defer r.unlock()
r.requestBody = matchBody(body)
return r
}
// WithBodyf formats according to a format specifier and use it as the expected body of the given request.
//
// Server.Expect(httpmock.MethodGet, "/path").
// WithBodyf("hello %s", "john)
func (r *Request) WithBodyf(format string, args ...any) *Request {
return r.WithBody(fmt.Sprintf(format, args...))
}
// WithBodyJSON marshals the object and use it as the expected body of the given request.
//
// Server.Expect(httpmock.MethodGet, "/path").
// WithBodyJSON(map[string]string{"foo": "bar"})
//
// nolint:unparam
func (r *Request) WithBodyJSON(v any) *Request {
body, err := json.Marshal(v)
if err != nil {
panic(err)
}
return r.WithBody(matcher.JSON(string(body)))
}
// ReturnCode sets the response code.
//
// Server.Expect(httpmock.MethodGet, "/path").
// ReturnCode(httpmock.StatusBadRequest)
func (r *Request) ReturnCode(code int) *Request {
r.lock()
defer r.unlock()
r.responseCode = code
return r
}
// ReturnHeader sets a response header.
//
// Server.Expect(httpmock.MethodGet, "/path").
// ReturnHeader("foo", "bar")
func (r *Request) ReturnHeader(header, value string) *Request {
r.lock()
defer r.unlock()
if r.responseHeader == nil {
r.responseHeader = map[string]string{}
}
r.responseHeader[header] = value
return r
}
// ReturnHeaders sets a list of response headers.
//
// Server.Expect(httpmock.MethodGet, "/path").
// ReturnHeaders(httpmock.Header{"foo": "bar"})
func (r *Request) ReturnHeaders(headers Header) *Request {
r.lock()
defer r.unlock()
r.responseHeader = headers
return r
}
// Return sets the result to return to client.
//
// Server.Expect(httpmock.MethodGet, "/path").
// Return("hello world!")
func (r *Request) Return(v any) *Request {
body := []byte(value.String(v))
return r.Run(func(*http.Request) ([]byte, error) {
return body, nil
})
}
// Returnf formats according to a format specifier and use it as the result to return to client.
//
// Server.Expect(httpmock.MethodGet, "/path").
// Returnf("hello %s", "john")
func (r *Request) Returnf(format string, args ...any) *Request {
return r.Return(fmt.Sprintf(format, args...))
}
// ReturnJSON marshals the object using json.Marshal and uses it as the result to return to client.
//
// Server.Expect(httpmock.MethodGet, "/path").
// ReturnJSON(map[string]string{"foo": "bar"})
func (r *Request) ReturnJSON(body any) *Request {
return r.Run(func(*http.Request) ([]byte, error) {
return json.Marshal(body)
})
}
// ReturnFile reads the file using ioutil.ReadFile and uses it as the result to return to client.
//
// Server.Expect(httpmock.MethodGet, "/path").
// ReturnFile("resources/fixtures/response.txt")
//
// nolint:unparam
func (r *Request) ReturnFile(filePath string) *Request {
filePath = filepath.Join(".", filepath.Clean(filePath))
_, err := os.Stat(filePath)
must.NotFail(err)
return r.Run(func(*http.Request) ([]byte, error) {
// nolint:gosec // filePath is cleaned above.
return os.ReadFile(filePath)
})
}
// Run sets the handler to handle a given request.
//
// Server.Expect(httpmock.MethodGet, "/path").
// Run(func(*http.Request) ([]byte, error) {
// return []byte("hello world!"), nil
// })
func (r *Request) Run(handle func(r *http.Request) ([]byte, error)) *Request {
r.lock()
defer r.unlock()
r.run = handle
return r
}
// handle runs the HTTP request.
func (r *Request) handle(w http.ResponseWriter, req *http.Request, defaultHeaders map[string]string) error {
// Block if specified.
if r.waitFor != nil {
<-r.waitFor
} else {
time.Sleep(r.waitTime)
}
body, err := r.run(req)
if err != nil {
_ = FailResponse(w, err.Error()) // nolint: errcheck
return err
}
for key, val := range mergeHeaders(r.responseHeader, defaultHeaders) {
w.Header().Set(key, val)
}
w.WriteHeader(r.responseCode)
_, err = w.Write(body)
return err
}
// Once indicates that the mock should only return the value once.
//
// Server.Expect(http.MethodGet, "/path").
// Return("hello world!").
// Once()
func (r *Request) Once() *Request {
return r.Times(1)
}
// Twice indicates that the mock should only return the value twice.
//
// Server.Expect(http.MethodGet, "/path").
// Return("hello world!").
// Twice()
func (r *Request) Twice() *Request {
return r.Times(2)
}
// UnlimitedTimes indicates that the mock should return the value at least once and there is no max limit in the number
// of return.
//
// Server.Expect(http.MethodGet, "/path").
// Return("hello world!").
// UnlimitedTimes()
func (r *Request) UnlimitedTimes() *Request {
return r.Times(0)
}
// Times indicates that the mock should only return the indicated number of times.
//
// Server.Expect(http.MethodGet, "/path").
// Return("hello world!").
// Times(5)
func (r *Request) Times(i int) *Request {
r.lock()
defer r.unlock()
r.repeatability = i
return r
}
// WaitUntil sets the channel that will block the mocked return until its closed
// or a message is received.
//
// Server.Expect(http.MethodGet, "/path").
// WaitUntil(time.After(time.Second)).
// Return("hello world!")
//
// nolint: unparam
func (r *Request) WaitUntil(w <-chan time.Time) *Request {
r.lock()
defer r.unlock()
r.waitFor = w
return r
}
// After sets how long to block until the call returns.
//
// Server.Expect(http.MethodGet, "/path").
// After(time.Second).
// Return("hello world!")
//
// nolint: unparam
func (r *Request) After(d time.Duration) *Request {
r.lock()
defer r.unlock()
r.waitTime = d
return r
}