-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttpstub.go
458 lines (412 loc) · 11 KB
/
httpstub.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package httpstub
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"sync"
"testing"
)
var _ http.Handler = (*Router)(nil)
type Router struct {
matchers []*matcher
server *httptest.Server
middlewares middlewareFuncs
requests []*http.Request
t *testing.T
useTLS bool
cacert, cert, key []byte
clientCacert, clientCert, clientKey []byte
mu sync.RWMutex
}
type matcher struct {
matchFuncs []matchFunc
handler http.HandlerFunc
middlewares middlewareFuncs
requests []*http.Request
router *Router
mu sync.RWMutex
}
type matchFunc func(r *http.Request) bool
type middlewareFunc func(next http.HandlerFunc) http.HandlerFunc
type middlewareFuncs []middlewareFunc
func (mws middlewareFuncs) then(fn http.HandlerFunc) http.HandlerFunc {
for i := range mws {
fn = mws[len(mws)-1-i](fn)
}
return fn
}
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rt.t.Helper()
r2 := cloneReq(r)
rt.mu.Lock()
rt.requests = append(rt.requests, r2)
rt.mu.Unlock()
for _, m := range rt.matchers {
match := true
for _, fn := range m.matchFuncs {
if !fn(r) {
match = false
}
}
if match {
m.mu.Lock()
m.requests = append(m.requests, r2)
m.mu.Unlock()
rt.mu.RLock()
mws := append(rt.middlewares, m.middlewares...)
rt.mu.RUnlock()
mws.then(m.handler).ServeHTTP(w, r)
return
}
}
dump, _ := httputil.DumpRequest(r, true)
rt.t.Errorf("httpstub error: request did not match\n---REQUEST START---\n%s\n---REQUEST END---\n", string(dump))
}
// NewRouter returns a new router with methods for stubbing.
func NewRouter(t *testing.T, opts ...Option) *Router {
t.Helper()
c := &config{}
for _, opt := range opts {
if err := opt(c); err != nil {
t.Fatal(err)
}
}
return &Router{
t: t,
useTLS: c.useTLS,
cacert: c.cacert,
cert: c.cert,
key: c.key,
clientCacert: c.clientCacert,
clientCert: c.clientCert,
clientKey: c.clientKey,
}
}
// NewServer returns a new router including *httptest.Server.
func NewServer(t *testing.T, opts ...Option) *Router {
t.Helper()
rt := NewRouter(t, opts...)
_ = rt.Server()
return rt
}
// NewTLSServer returns a new router including TLS *httptest.Server.
func NewTLSServer(t *testing.T, opts ...Option) *Router {
t.Helper()
rt := NewRouter(t, opts...)
rt.useTLS = true
_ = rt.TLSServer()
return rt
}
// Client returns *http.Client which requests *httptest.Server.
func (rt *Router) Client() *http.Client {
if rt.server == nil {
rt.t.Error("server is not started yet")
return nil
}
return rt.server.Client()
}
// Server returns *httptest.Server with *Router set.
func (rt *Router) Server() *httptest.Server {
if rt.server != nil {
return rt.server
}
if rt.useTLS {
rt.server = httptest.NewUnstartedServer(rt)
// server certificates
if rt.cert != nil && rt.key != nil {
cert, err := tls.X509KeyPair(rt.cert, rt.key)
if err != nil {
panic(err)
}
existingConfig := rt.server.TLS
if existingConfig != nil {
rt.server.TLS = existingConfig.Clone()
} else {
rt.server.TLS = new(tls.Config)
}
rt.server.TLS.Certificates = []tls.Certificate{cert}
}
// client CA
if rt.clientCacert != nil {
certpool, err := x509.SystemCertPool()
if err != nil {
// FIXME for Windows
// ref: https://github.com/golang/go/issues/18609
certpool = x509.NewCertPool()
}
if !certpool.AppendCertsFromPEM(rt.clientCacert) {
panic("failed to add cacert")
}
existingConfig := rt.server.TLS
if existingConfig != nil {
rt.server.TLS = existingConfig.Clone()
} else {
rt.server.TLS = new(tls.Config)
}
rt.server.TLS.ClientCAs = certpool
rt.server.TLS.ClientAuth = tls.RequireAndVerifyClientCert
}
rt.server.StartTLS()
// server CA
if rt.cacert != nil {
certpool, err := x509.SystemCertPool()
if err != nil {
// FIXME for Windows
// ref: https://github.com/golang/go/issues/18609
certpool = x509.NewCertPool()
}
if !certpool.AppendCertsFromPEM(rt.cacert) {
panic("failed to add cacert")
}
client := rt.server.Client()
client.Transport.(*http.Transport).TLSClientConfig.RootCAs = certpool
}
// client certificates
if rt.clientCert != nil && rt.clientKey != nil {
cert, err := tls.X509KeyPair(rt.clientCert, rt.clientKey)
if err != nil {
panic(err)
}
client := rt.server.Client()
client.Transport.(*http.Transport).TLSClientConfig.Certificates = []tls.Certificate{cert}
}
} else {
rt.server = httptest.NewServer(rt)
}
client := rt.server.Client()
tp := client.Transport.(*http.Transport)
client.Transport = newTransport(rt.server.URL, tp)
return rt.server
}
// TLSServer returns TLS *httptest.Server with *Router set.
func (rt *Router) TLSServer() *httptest.Server {
rt.useTLS = true
return rt.Server()
}
// Close shuts down *httptest.Server
func (rt *Router) Close() {
if rt.server == nil {
rt.t.Error("server is not started yet")
return
}
rt.server.Close()
}
// Match create request matcher with matchFunc (func(r *http.Request) bool).
func (rt *Router) Match(fn func(r *http.Request) bool) *matcher {
m := &matcher{
matchFuncs: []matchFunc{fn},
router: rt,
}
rt.mu.Lock()
defer rt.mu.Unlock()
rt.matchers = append(rt.matchers, m)
return m
}
// Match append matchFunc (func(r *http.Request) bool) to request matcher.
func (m *matcher) Match(fn func(r *http.Request) bool) *matcher {
m.mu.Lock()
defer m.mu.Unlock()
m.matchFuncs = append(m.matchFuncs, fn)
return m
}
// Method create request matcher using method.
func (rt *Router) Method(method string) *matcher {
rt.mu.Lock()
defer rt.mu.Unlock()
fn := methodMatchFunc(method)
m := &matcher{
matchFuncs: []matchFunc{fn},
router: rt,
}
rt.matchers = append(rt.matchers, m)
return m
}
// Method append matcher using method to request matcher.
func (m *matcher) Method(method string) *matcher {
m.mu.Lock()
defer m.mu.Unlock()
fn := methodMatchFunc(method)
m.matchFuncs = append(m.matchFuncs, fn)
return m
}
// Path create request matcher using path.
func (rt *Router) Path(path string) *matcher {
rt.mu.Lock()
defer rt.mu.Unlock()
fn := pathMatchFunc(path)
m := &matcher{
matchFuncs: []matchFunc{fn},
}
rt.matchers = append(rt.matchers, m)
return m
}
// Path append matcher using path to request matcher.
func (m *matcher) Path(path string) *matcher {
m.mu.Lock()
defer m.mu.Unlock()
fn := pathMatchFunc(path)
m.matchFuncs = append(m.matchFuncs, fn)
return m
}
// Pathf create request matcher using sprintf-ed path.
func (rt *Router) Pathf(format string, a ...any) *matcher {
return rt.Path(fmt.Sprintf(format, a...))
}
// Pathf append matcher using sprintf-ed path to request matcher.
func (m *matcher) Pathf(format string, a ...any) *matcher {
return m.Path(fmt.Sprintf(format, a...))
}
// DefaultMiddleware append default middleware.
func (rt *Router) DefaultMiddleware(mw func(next http.HandlerFunc) http.HandlerFunc) {
rt.mu.Lock()
defer rt.mu.Unlock()
rt.middlewares = append(rt.middlewares, mw)
}
// DefaultHeader append default middleware which append header.
func (rt *Router) DefaultHeader(key, value string) {
rt.mu.Lock()
defer rt.mu.Unlock()
mw := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(key, value)
next.ServeHTTP(w, r)
}
}
rt.middlewares = append(rt.middlewares, mw)
}
// Middleware append middleware to matcher.
func (m *matcher) Middleware(mw func(next http.HandlerFunc) http.HandlerFunc) *matcher {
m.mu.Lock()
defer m.mu.Unlock()
m.middlewares = append(m.middlewares, mw)
return m
}
// Header append middleware which append header to response.
func (m *matcher) Header(key, value string) *matcher {
m.mu.Lock()
defer m.mu.Unlock()
mw := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(key, value)
next.ServeHTTP(w, r)
}
}
m.middlewares = append(m.middlewares, mw)
return m
}
// Handler set handler.
func (m *matcher) Handler(fn func(w http.ResponseWriter, r *http.Request)) {
m.handler = http.HandlerFunc(fn)
}
// Response set handler which return response (status and body).
func (m *matcher) Response(status int, body []byte) {
fn := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
_, _ = w.Write(body)
}
m.handler = http.HandlerFunc(fn)
}
// ResponseString set handler which return response (status and string-body).
func (m *matcher) ResponseString(status int, body string) {
b := []byte(body)
m.Response(status, b)
}
// ResponseStringf set handler which return response (status and sprintf-ed-body).
func (m *matcher) ResponseStringf(status int, format string, a ...any) {
b := []byte(fmt.Sprintf(format, a...))
m.Response(status, b)
}
// Requests returns []*http.Request received by router.
func (rt *Router) Requests() []*http.Request {
rt.mu.RLock()
defer rt.mu.RUnlock()
return rt.requests
}
// Requests returns []*http.Request received by matcher.
func (m *matcher) Requests() []*http.Request {
m.mu.RLock()
defer m.mu.RUnlock()
return m.requests
}
// ClearRequests clear []*http.Request received by router.
func (rt *Router) ClearRequests() {
rt.mu.RLock()
defer rt.mu.RUnlock()
rt.requests = nil
for _, m := range rt.matchers {
m.ClearRequests()
}
}
// ClearRequests returns []*http.Request received by matcher.
func (m *matcher) ClearRequests() {
m.mu.RLock()
defer m.mu.RUnlock()
requests := []*http.Request{}
L:
for _, r := range m.router.requests {
for _, mr := range m.requests {
if r == mr {
continue L
}
}
requests = append(requests, r)
}
m.router.requests = requests
m.requests = nil
}
func cloneReq(r *http.Request) *http.Request {
r2 := r.Clone(r.Context())
body, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewReader(body))
r2.Body = io.NopCloser(bytes.NewReader(body))
return r2
}
func methodMatchFunc(method string) matchFunc {
return func(r *http.Request) bool {
return r.Method == method
}
}
func pathMatchFunc(path string) matchFunc {
pathRe := regexp.MustCompile(strings.Replace(path, "/*", "/.*", -1))
return func(r *http.Request) bool {
return pathRe.MatchString(r.URL.Path)
}
}
type transport struct {
URL *url.URL
tp *http.Transport
}
func newTransport(rawURL string, tp *http.Transport) http.RoundTripper {
u, _ := url.Parse(rawURL)
return &transport{
URL: u,
tp: tp,
}
}
func (t *transport) transport() http.RoundTripper {
return t.tp
}
func (t *transport) CancelRequest(r *http.Request) {
type canceler interface {
CancelRequest(*http.Request)
}
if cr, ok := t.transport().(canceler); ok {
cr.CancelRequest(r)
}
}
func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) {
r.URL.Scheme = t.URL.Scheme
r.URL.Host = t.URL.Host
r.URL.User = t.URL.User
r.URL.Opaque = t.URL.Opaque
res, err := t.transport().RoundTrip(r)
return res, err
}