-
Notifications
You must be signed in to change notification settings - Fork 18
/
recorder.go
97 lines (82 loc) · 1.79 KB
/
recorder.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
package httprecorder
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"sync"
)
type Request struct {
Method string
URL url.URL
Header http.Header
Body []byte
}
func (r *Request) StringBody() string {
return string(r.Body)
}
// Decode decodes the JSON from the request into the supplied pointer
func (r *Request) Decode(x interface{}) error {
return json.Unmarshal(r.Body, x)
}
type RequestRecorder struct {
mu sync.RWMutex
requests []Request
}
func New() *RequestRecorder {
return &RequestRecorder{}
}
// Record stores a copy of the incoming request ensuring the body can still
// be consumed by the caller
func (r *RequestRecorder) Record(request *http.Request) (err error) {
req := Request{
Method: request.Method,
URL: *request.URL,
}
req.Header = make(http.Header)
for k, v := range request.Header {
req.Header[k] = v
}
req.Body, err = io.ReadAll(request.Body)
if err != nil {
return err
}
request.Body = io.NopCloser(bytes.NewReader(req.Body))
r.mu.Lock()
defer r.mu.Unlock()
r.requests = append(r.requests, req)
return nil
}
func (r *RequestRecorder) Reset() {
r.mu.Lock()
defer r.mu.Unlock()
r.requests = nil
}
func (r *RequestRecorder) AllRequests() []Request {
r.mu.RLock()
defer r.mu.RUnlock()
requests := make([]Request, len(r.requests))
copy(requests, r.requests)
return requests
}
func (r *RequestRecorder) LastRequest() *Request {
r.mu.RLock()
defer r.mu.RUnlock()
if len(r.requests) == 0 {
return nil
}
req := r.requests[len(r.requests)-1]
return &req
}
func (r *RequestRecorder) FindRequests(method string, u url.URL) []Request {
r.mu.RLock()
defer r.mu.RUnlock()
var requests []Request
for _, req := range r.requests {
if req.Method == method && req.URL == u {
requests = append(requests, req)
}
}
return requests
}