-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.go
48 lines (42 loc) · 1.33 KB
/
transform.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
package hypert
import (
"bytes"
"encoding/json"
"io"
"net/http"
)
// ResponseTransform is a type that can transform a response, in case the real one is not feasible for test.
// Use WithResponseTransform option to apply transformations to the response.
type ResponseTransform interface {
TransformResponse(r *http.Response) *http.Response
}
// ResponseTransformFunc is a convenience type that implements ResponseTransform interface.
type ResponseTransformFunc func(r *http.Response) *http.Response
func (f ResponseTransformFunc) TransformResponse(r *http.Response) *http.Response {
return f(r)
}
// ComposeTransforms composes multiple transforms into a single one.
func ComposeTransforms(transforms ...ResponseTransform) ResponseTransform {
return ResponseTransformFunc(func(r *http.Response) *http.Response {
for _, transform := range transforms {
r = transform.TransformResponse(r)
}
return r
})
}
// TransformResponseFormatJSON formats json so it's easier to read.
func TransformResponseFormatJSON() ResponseTransform {
return ResponseTransformFunc(func(r *http.Response) *http.Response {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
return r
}
var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, bodyBytes, "", " ")
if err != nil {
return r
}
r.Body = io.NopCloser(&prettyJSON)
return r
})
}