-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinspector.go
78 lines (63 loc) · 1.46 KB
/
inspector.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
package httpsling
import (
"bytes"
"io"
"net/http"
)
// Inspect installs and returns an Inspector
func Inspect(r *Requester) *Inspector {
i := Inspector{}
r.MustApply(&i)
return &i
}
// Inspector is a Requester Option which captures requests and responses
type Inspector struct {
// The last request sent by the client
Request *http.Request
// The last response received by the client
Response *http.Response
// The last client request body
RequestBody *bytes.Buffer
// The last client response body
ResponseBody *bytes.Buffer
}
// Clear clears the inspector's fields
func (i *Inspector) Clear() {
if i == nil {
return
}
i.RequestBody = nil
i.ResponseBody = nil
i.Request = nil
i.Response = nil
}
// Apply implements Option
func (i *Inspector) Apply(r *Requester) error {
return r.Apply(Middleware(i.Wrap))
}
// Wrap implements Middleware
func (i *Inspector) Wrap(next Doer) Doer {
return DoerFunc(func(req *http.Request) (*http.Response, error) {
i.Request = req
req.Body = i.wrap(req.Body, true)
resp, err := next.Do(req)
i.Response = resp
if resp != nil {
resp.Body = i.wrap(resp.Body, false)
}
return resp, err
})
}
func (i *Inspector) wrap(body io.ReadCloser, isRequest bool) io.ReadCloser {
if body != nil {
out, _ := io.ReadAll(body)
body.Close()
body = io.NopCloser(bytes.NewReader(out))
if isRequest {
i.RequestBody = bytes.NewBuffer(out)
} else {
i.ResponseBody = bytes.NewBuffer(out)
}
}
return body
}