-
Notifications
You must be signed in to change notification settings - Fork 103
/
response.go
782 lines (732 loc) · 23.8 KB
/
response.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
package httpmock
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/jarcoal/httpmock/internal"
)
// fromThenKeyType is used by Then().
type fromThenKeyType struct{}
var fromThenKey = fromThenKeyType{}
type suggestedInfo struct {
kind string
suggested string
}
// suggestedMethodKeyType is used by NewNotFoundResponder().
type suggestedKeyType struct{}
var suggestedKey = suggestedKeyType{}
// Responder is a callback that receives an [*http.Request] and returns
// a mocked response.
type Responder func(*http.Request) (*http.Response, error)
func (r Responder) times(name string, n int, fn ...func(...any)) Responder {
count := 0
return func(req *http.Request) (*http.Response, error) {
count++
if count > n {
err := internal.StackTracer{
Err: fmt.Errorf("Responder not found for %s %s (coz %s and already called %d times)", req.Method, req.URL, name, count),
}
if len(fn) > 0 {
err.CustomFn = fn[0]
}
return nil, err
}
return r(req)
}
}
// Times returns a [Responder] callable n times before returning an
// error. If the [Responder] is called more than n times and fn is
// passed and non-nil, it acts as the fn parameter of
// [NewNotFoundResponder], allowing to dump the stack trace to
// localize the origin of the call.
//
// import (
// "testing"
// "github.com/jarcoal/httpmock"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// // This responder is callable 3 times, then an error is returned and
// // the stacktrace of the call logged using t.Log()
// httpmock.RegisterResponder("GET", "/foo/bar",
// httpmock.NewStringResponder(200, "{}").Times(3, t.Log),
// )
func (r Responder) Times(n int, fn ...func(...any)) Responder {
return r.times("Times", n, fn...)
}
// Once returns a new [Responder] callable once before returning an
// error. If the [Responder] is called 2 or more times and fn is passed
// and non-nil, it acts as the fn parameter of [NewNotFoundResponder],
// allowing to dump the stack trace to localize the origin of the
// call.
//
// import (
// "testing"
// "github.com/jarcoal/httpmock"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// // This responder is callable only once, then an error is returned and
// // the stacktrace of the call logged using t.Log()
// httpmock.RegisterResponder("GET", "/foo/bar",
// httpmock.NewStringResponder(200, "{}").Once(t.Log),
// )
func (r Responder) Once(fn ...func(...any)) Responder {
return r.times("Once", 1, fn...)
}
// Trace returns a new [Responder] that allows to easily trace the calls
// of the original [Responder] using fn. It can be used in conjunction
// with the testing package as in the example below with the help of
// [*testing.T.Log] method:
//
// import (
// "testing"
// "github.com/jarcoal/httpmock"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// httpmock.RegisterResponder("GET", "/foo/bar",
// httpmock.NewStringResponder(200, "{}").Trace(t.Log),
// )
func (r Responder) Trace(fn func(...any)) Responder {
return func(req *http.Request) (*http.Response, error) {
resp, err := r(req)
return resp, internal.StackTracer{
CustomFn: fn,
Err: err,
}
}
}
// Delay returns a new [Responder] that calls the original r Responder
// after a delay of d.
//
// import (
// "testing"
// "time"
// "github.com/jarcoal/httpmock"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// httpmock.RegisterResponder("GET", "/foo/bar",
// httpmock.NewStringResponder(200, "{}").Delay(100*time.Millisecond),
// )
func (r Responder) Delay(d time.Duration) Responder {
return func(req *http.Request) (*http.Response, error) {
time.Sleep(d)
return r(req)
}
}
var errThenDone = errors.New("ThenDone")
// similar is simple but a bit tricky. Here we consider two Responder
// are similar if they share the same function, but not necessarily
// the same environment. It is only used by Then below.
func (r Responder) similar(other Responder) bool {
return reflect.ValueOf(r).Pointer() == reflect.ValueOf(other).Pointer()
}
// Then returns a new [Responder] that calls r on first invocation, then
// next on following ones, except when Then is chained, in this case
// next is called only once:
//
// A := httpmock.NewStringResponder(200, "A")
// B := httpmock.NewStringResponder(200, "B")
// C := httpmock.NewStringResponder(200, "C")
//
// httpmock.RegisterResponder("GET", "/pipo", A.Then(B).Then(C))
//
// http.Get("http://foo.bar/pipo") // A is called
// http.Get("http://foo.bar/pipo") // B is called
// http.Get("http://foo.bar/pipo") // C is called
// http.Get("http://foo.bar/pipo") // C is called, and so on
//
// A panic occurs if next is the result of another Then call (because
// allowing it could cause inextricable problems at runtime). Then
// calls can be chained, but cannot call each other by
// parameter. Example:
//
// A.Then(B).Then(C) // is OK
// A.Then(B.Then(C)) // panics as A.Then() parameter is another Then() call
//
// See also [ResponderFromMultipleResponses].
func (r Responder) Then(next Responder) (x Responder) {
var done int
var mu sync.Mutex
x = func(req *http.Request) (*http.Response, error) {
mu.Lock()
defer mu.Unlock()
ctx := req.Context()
thenCalledUs, _ := ctx.Value(fromThenKey).(bool)
if !thenCalledUs {
req = req.WithContext(context.WithValue(ctx, fromThenKey, true))
}
switch done {
case 0:
resp, err := r(req)
if err != errThenDone {
if !x.similar(r) { // r is NOT a Then
done = 1
}
return resp, err
}
fallthrough
case 1:
done = 2 // next is NEVER a Then, as it is forbidden by design
return next(req)
}
if thenCalledUs {
return nil, errThenDone
}
return next(req)
}
if next.similar(x) {
panic("Then() does not accept another Then() Responder as parameter")
}
return
}
// SetContentLength returns a new [Responder] based on r that ensures
// the returned [*http.Response] ContentLength field and
// Content-Length header are set to the right value.
//
// If r returns an [*http.Response] with a nil Body or equal to
// [http.NoBody], the length is always set to 0.
//
// If r returned response.Body implements:
//
// Len() int
//
// then the length is set to the Body.Len() returned value. All
// httpmock generated bodies implement this method. Beware that
// [strings.Builder], [strings.Reader], [bytes.Buffer] and
// [bytes.Reader] types used with [io.NopCloser] do not implement
// Len() anymore.
//
// Otherwise, r returned response.Body is entirely copied into an
// internal buffer to get its length, then it is closed. The Body of
// the [*http.Response] returned by the [Responder] returned by
// SetContentLength can then be read again to return its content as
// usual. But keep in mind that each time this [Responder] is called,
// r is called first. So this one has to carefully handle its body: it
// is highly recommended to use [NewRespBodyFromString] or
// [NewRespBodyFromBytes] to set the body once (as
// [NewStringResponder] and [NewBytesResponder] do behind the scene),
// or to build the body each time r is called.
//
// The following calls are all correct:
//
// responder = httpmock.NewStringResponder(200, "BODY").SetContentLength()
// responder = httpmock.NewBytesResponder(200, []byte("BODY")).SetContentLength()
// responder = ResponderFromResponse(&http.Response{
// // build a body once, but httpmock knows how to "rearm" it once read
// Body: NewRespBodyFromString("BODY"),
// StatusCode: 200,
// }).SetContentLength()
// responder = httpmock.Responder(func(req *http.Request) (*http.Response, error) {
// // build a new body for each call
// return &http.Response{
// StatusCode: 200,
// Body: io.NopCloser(strings.NewReader("BODY")),
// }, nil
// }).SetContentLength()
//
// But the following is not correct:
//
// responder = httpmock.ResponderFromResponse(&http.Response{
// StatusCode: 200,
// Body: io.NopCloser(strings.NewReader("BODY")),
// }).SetContentLength()
//
// it will only succeed for the first responder call. The following
// calls will deliver responses with an empty body, as it will already
// been read by the first call.
func (r Responder) SetContentLength() Responder {
return func(req *http.Request) (*http.Response, error) {
resp, err := r(req)
if err != nil {
return nil, err
}
nr := *resp
switch nr.Body {
case nil:
nr.Body = http.NoBody
fallthrough
case http.NoBody:
nr.ContentLength = 0
default:
bl, ok := nr.Body.(interface{ Len() int })
if !ok {
copyBody := &dummyReadCloser{orig: nr.Body}
bl, nr.Body = copyBody, copyBody
}
nr.ContentLength = int64(bl.Len())
}
if nr.Header == nil {
nr.Header = http.Header{}
}
nr.Header = nr.Header.Clone()
nr.Header.Set("Content-Length", strconv.FormatInt(nr.ContentLength, 10))
return &nr, nil
}
}
// HeaderAdd returns a new [Responder] based on r that ensures the
// returned [*http.Response] includes h header. It adds each h entry
// to the header. It appends to any existing values associated with
// each h key. Each key is case insensitive; it is canonicalized by
// [http.CanonicalHeaderKey].
//
// See also [Responder.HeaderSet] and [Responder.SetContentLength].
func (r Responder) HeaderAdd(h http.Header) Responder {
return func(req *http.Request) (*http.Response, error) {
resp, err := r(req)
if err != nil {
return nil, err
}
nr := *resp
if nr.Header == nil {
nr.Header = make(http.Header, len(h))
}
nr.Header = nr.Header.Clone()
for k, v := range h {
k = http.CanonicalHeaderKey(k)
if v == nil {
if _, ok := nr.Header[k]; !ok {
nr.Header[k] = nil
}
continue
}
nr.Header[k] = append(nr.Header[k], v...)
}
return &nr, nil
}
}
// HeaderSet returns a new [Responder] based on r that ensures the
// returned [*http.Response] includes h header. It sets the header
// entries associated with each h key. It replaces any existing values
// associated each h key. Each key is case insensitive; it is
// canonicalized by [http.CanonicalHeaderKey].
//
// See also [Responder.HeaderAdd] and [Responder.SetContentLength].
func (r Responder) HeaderSet(h http.Header) Responder {
return func(req *http.Request) (*http.Response, error) {
resp, err := r(req)
if err != nil {
return nil, err
}
nr := *resp
if nr.Header == nil {
nr.Header = make(http.Header, len(h))
}
nr.Header = nr.Header.Clone()
for k, v := range h {
k = http.CanonicalHeaderKey(k)
if v == nil {
nr.Header[k] = nil
continue
}
nr.Header[k] = append([]string(nil), v...)
}
return &nr, nil
}
}
// ResponderFromResponse wraps an [*http.Response] in a [Responder].
//
// Be careful, except for responses generated by httpmock
// ([NewStringResponse] and [NewBytesResponse] functions) for which
// there is no problems, it is the caller responsibility to ensure the
// response body can be read several times and concurrently if needed,
// as it is shared among all [Responder] returned responses.
//
// For home-made responses, [NewRespBodyFromString] and
// [NewRespBodyFromBytes] functions can be used to produce response
// bodies that can be read several times and concurrently.
func ResponderFromResponse(resp *http.Response) Responder {
return func(req *http.Request) (*http.Response, error) {
res := *resp
// Our stuff: generate a new io.ReadCloser instance sharing the same buffer
if body, ok := resp.Body.(*dummyReadCloser); ok {
res.Body = body.copy()
}
res.Request = req
return &res, nil
}
}
// ResponderFromMultipleResponses wraps an [*http.Response] list in a
// [Responder].
//
// Each response will be returned in the order of the provided list.
// If the [Responder] is called more than the size of the provided
// list, an error will be thrown.
//
// Be careful, except for responses generated by httpmock
// ([NewStringResponse] and [NewBytesResponse] functions) for which
// there is no problems, it is the caller responsibility to ensure the
// response body can be read several times and concurrently if needed,
// as it is shared among all [Responder] returned responses.
//
// For home-made responses, [NewRespBodyFromString] and
// [NewRespBodyFromBytes] functions can be used to produce response
// bodies that can be read several times and concurrently.
//
// If all responses have been returned and fn is passed and non-nil,
// it acts as the fn parameter of [NewNotFoundResponder], allowing to
// dump the stack trace to localize the origin of the call.
//
// import (
// "github.com/jarcoal/httpmock"
// "testing"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// // This responder is callable only once, then an error is returned and
// // the stacktrace of the call logged using t.Log()
// httpmock.RegisterResponder("GET", "/foo/bar",
// httpmock.ResponderFromMultipleResponses(
// []*http.Response{
// httpmock.NewStringResponse(200, `{"name":"bar"}`),
// httpmock.NewStringResponse(404, `{"mesg":"Not found"}`),
// },
// t.Log),
// )
// }
//
// See also [Responder.Then].
func ResponderFromMultipleResponses(responses []*http.Response, fn ...func(...any)) Responder {
responseIndex := 0
mutex := sync.Mutex{}
return func(req *http.Request) (*http.Response, error) {
mutex.Lock()
defer mutex.Unlock()
defer func() { responseIndex++ }()
if responseIndex >= len(responses) {
err := internal.StackTracer{
Err: fmt.Errorf("not enough responses provided: responder called %d time(s) but %d response(s) provided", responseIndex+1, len(responses)),
}
if len(fn) > 0 {
err.CustomFn = fn[0]
}
return nil, err
}
res := *responses[responseIndex]
// Our stuff: generate a new io.ReadCloser instance sharing the same buffer
if body, ok := responses[responseIndex].Body.(*dummyReadCloser); ok {
res.Body = body.copy()
}
res.Request = req
return &res, nil
}
}
// NewErrorResponder creates a [Responder] that returns an empty request and the
// given error. This can be used to e.g. imitate more deep http errors for the
// client.
func NewErrorResponder(err error) Responder {
return func(req *http.Request) (*http.Response, error) {
return nil, err
}
}
// NewNotFoundResponder creates a [Responder] typically used in
// conjunction with [RegisterNoResponder] function and [testing]
// package, to be proactive when a [Responder] is not found. fn is
// called with a unique string parameter containing the name of the
// missing route and the stack trace to localize the origin of the
// call. If fn returns (= if it does not panic), the [Responder] returns
// an error of the form: "Responder not found for GET http://foo.bar/path".
// Note that fn can be nil.
//
// It is useful when writing tests to ensure that all routes have been
// mocked.
//
// Example of use:
//
// import (
// "testing"
// "github.com/jarcoal/httpmock"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// // Calls testing.Fatal with the name of Responder-less route and
// // the stack trace of the call.
// httpmock.RegisterNoResponder(httpmock.NewNotFoundResponder(t.Fatal))
//
// Will abort the current test and print something like:
//
// transport_test.go:735: Called from net/http.Get()
// at /go/src/github.com/jarcoal/httpmock/transport_test.go:714
// github.com/jarcoal/httpmock.TestCheckStackTracer()
// at /go/src/testing/testing.go:865
// testing.tRunner()
// at /go/src/runtime/asm_amd64.s:1337
func NewNotFoundResponder(fn func(...any)) Responder {
return func(req *http.Request) (*http.Response, error) {
var extra string
suggested, _ := req.Context().Value(suggestedKey).(*suggestedInfo)
if suggested != nil {
if suggested.kind == "matcher" {
extra = fmt.Sprintf(` despite %s`, suggested.suggested)
} else {
extra = fmt.Sprintf(`, but one matches %s %q`, suggested.kind, suggested.suggested)
}
}
return nil, internal.StackTracer{
CustomFn: fn,
Err: fmt.Errorf("Responder not found for %s %s%s", req.Method, req.URL, extra),
}
}
}
// NewStringResponse creates an [*http.Response] with a body based on
// the given string. Also accepts an HTTP status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewStringResponse(200, httpmock.File("body.txt").String())
func NewStringResponse(status int, body string) *http.Response {
return &http.Response{
Status: fmt.Sprintf("%03d %s", status, http.StatusText(status)),
StatusCode: status,
Body: NewRespBodyFromString(body),
Header: http.Header{},
ContentLength: -1,
}
}
// NewStringResponder creates a [Responder] from a given body (as a
// string) and status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewStringResponder(200, httpmock.File("body.txt").String())
func NewStringResponder(status int, body string) Responder {
return ResponderFromResponse(NewStringResponse(status, body))
}
// NewBytesResponse creates an [*http.Response] with a body based on the
// given bytes. Also accepts an HTTP status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewBytesResponse(200, httpmock.File("body.raw").Bytes())
func NewBytesResponse(status int, body []byte) *http.Response {
return &http.Response{
Status: fmt.Sprintf("%03d %s", status, http.StatusText(status)),
StatusCode: status,
Body: NewRespBodyFromBytes(body),
Header: http.Header{},
ContentLength: -1,
}
}
// NewBytesResponder creates a [Responder] from a given body (as a byte
// slice) and status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewBytesResponder(200, httpmock.File("body.raw").Bytes())
func NewBytesResponder(status int, body []byte) Responder {
return ResponderFromResponse(NewBytesResponse(status, body))
}
// NewJsonResponse creates an [*http.Response] with a body that is a
// JSON encoded representation of the given any. Also accepts
// an HTTP status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewJsonResponse(200, httpmock.File("body.json"))
func NewJsonResponse(status int, body any) (*http.Response, error) { //nolint: revive
encoded, err := json.Marshal(body)
if err != nil {
return nil, err
}
response := NewBytesResponse(status, encoded)
response.Header.Set("Content-Type", "application/json")
return response, nil
}
// NewJsonResponseOrPanic is like [NewJsonResponse] but panics in case of error.
//
// It simplifies the call of [ResponderFromMultipleResponses], avoiding the
// use of a temporary variable and an error check, and so can be used in such
// context:
//
// httpmock.RegisterResponder(
// "GET",
// "/test/path",
// httpmock.ResponderFromMultipleResponses([]*http.Response{
// httpmock.NewJsonResponseOrPanic(200, &MyFirstResponseBody),
// httpmock.NewJsonResponseOrPanic(200, &MySecondResponseBody),
// }),
// )
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewJsonResponseOrPanic(200, httpmock.File("body.json"))
func NewJsonResponseOrPanic(status int, body any) *http.Response { //nolint: revive
response, err := NewJsonResponse(status, body)
if err != nil {
panic(err)
}
return response
}
// NewJsonResponder creates a [Responder] from a given body (as an
// any that is encoded to JSON) and status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewJsonResponder(200, httpmock.File("body.json"))
func NewJsonResponder(status int, body any) (Responder, error) { //nolint: revive
resp, err := NewJsonResponse(status, body)
if err != nil {
return nil, err
}
return ResponderFromResponse(resp), nil
}
// NewJsonResponderOrPanic is like [NewJsonResponder] but panics in
// case of error.
//
// It simplifies the call of [RegisterResponder], avoiding the use of a
// temporary variable and an error check, and so can be used as
// [NewStringResponder] or [NewBytesResponder] in such context:
//
// httpmock.RegisterResponder(
// "GET",
// "/test/path",
// httpmock.NewJsonResponderOrPanic(200, &MyBody),
// )
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewJsonResponderOrPanic(200, httpmock.File("body.json"))
func NewJsonResponderOrPanic(status int, body any) Responder { //nolint: revive
responder, err := NewJsonResponder(status, body)
if err != nil {
panic(err)
}
return responder
}
// NewXmlResponse creates an [*http.Response] with a body that is an
// XML encoded representation of the given any. Also accepts an HTTP
// status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewXmlResponse(200, httpmock.File("body.xml"))
func NewXmlResponse(status int, body any) (*http.Response, error) { //nolint: revive
var (
encoded []byte
err error
)
if f, ok := body.(File); ok {
encoded, err = f.bytes()
} else {
encoded, err = xml.Marshal(body)
}
if err != nil {
return nil, err
}
response := NewBytesResponse(status, encoded)
response.Header.Set("Content-Type", "application/xml")
return response, nil
}
// NewXmlResponder creates a [Responder] from a given body (as an
// any that is encoded to XML) and status code.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewXmlResponder(200, httpmock.File("body.xml"))
func NewXmlResponder(status int, body any) (Responder, error) { //nolint: revive
resp, err := NewXmlResponse(status, body)
if err != nil {
return nil, err
}
return ResponderFromResponse(resp), nil
}
// NewXmlResponderOrPanic is like [NewXmlResponder] but panics in case
// of error.
//
// It simplifies the call of [RegisterResponder], avoiding the use of a
// temporary variable and an error check, and so can be used as
// [NewStringResponder] or [NewBytesResponder] in such context:
//
// httpmock.RegisterResponder(
// "GET",
// "/test/path",
// httpmock.NewXmlResponderOrPanic(200, &MyBody),
// )
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewXmlResponderOrPanic(200, httpmock.File("body.xml"))
func NewXmlResponderOrPanic(status int, body any) Responder { //nolint: revive
responder, err := NewXmlResponder(status, body)
if err != nil {
panic(err)
}
return responder
}
// NewRespBodyFromString creates an [io.ReadCloser] from a string that
// is suitable for use as an HTTP response body.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewRespBodyFromString(httpmock.File("body.txt").String())
func NewRespBodyFromString(body string) io.ReadCloser {
return &dummyReadCloser{orig: body}
}
// NewRespBodyFromBytes creates an [io.ReadCloser] from a byte slice
// that is suitable for use as an HTTP response body.
//
// To pass the content of an existing file as body use [File] as in:
//
// httpmock.NewRespBodyFromBytes(httpmock.File("body.txt").Bytes())
func NewRespBodyFromBytes(body []byte) io.ReadCloser {
return &dummyReadCloser{orig: body}
}
type lenReadSeeker interface {
io.ReadSeeker
Len() int
}
type dummyReadCloser struct {
orig any // string or []byte
body lenReadSeeker // instanciated on demand from orig
}
// copy returns a new instance resetting d.body to nil.
func (d *dummyReadCloser) copy() *dummyReadCloser {
return &dummyReadCloser{orig: d.orig}
}
// setup ensures d.body is correctly initialized.
func (d *dummyReadCloser) setup() {
if d.body == nil {
switch body := d.orig.(type) {
case string:
d.body = strings.NewReader(body)
case []byte:
d.body = bytes.NewReader(body)
case io.ReadCloser:
var buf bytes.Buffer
io.Copy(&buf, body) //nolint: errcheck
body.Close()
d.body = bytes.NewReader(buf.Bytes())
}
}
}
func (d *dummyReadCloser) Read(p []byte) (n int, err error) {
d.setup()
return d.body.Read(p)
}
func (d *dummyReadCloser) Close() error {
d.setup()
d.body.Seek(0, io.SeekEnd) //nolint: errcheck
return nil
}
func (d *dummyReadCloser) Len() int {
d.setup()
return d.body.Len()
}