-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
82 lines (68 loc) · 1.59 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
package http
import (
"encoding/json"
"io"
"net/http"
"github.com/element84/swoop-go/pkg/config/jsonpath"
"github.com/element84/swoop-go/pkg/config/regexp"
)
type Response struct {
StatusCode int
Body string
Json any `json:"-"`
}
func wrapRequest(resp *http.Response, err error) (*Response, error) {
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// TODO: check content type before trying this
bodyJson := map[string]any{}
err = json.Unmarshal([]byte(body), &bodyJson)
if err != nil {
// not a json body, no worries, just set to nil
bodyJson = nil
}
return &Response{
resp.StatusCode,
string(body),
bodyJson,
}, nil
}
type responseMatcher struct {
StatusCode int `yaml:"statusCode"`
JsonPath *jsonpath.JsonPath `yaml:"jsonPath"`
Message *regexp.Regexp `yaml:"message"`
Result RequestResult `yaml:"result"`
}
func (rm *responseMatcher) match(resp *Response) (matched bool, err error) {
if rm.StatusCode != resp.StatusCode {
return false, nil
}
if rm.Message != nil && !rm.Message.MatchString(resp.Body) {
return false, nil
}
if rm.JsonPath != nil {
if !rm.JsonPath.Has(resp.Json) {
return false, nil
}
}
return true, rm.Result.ToError()
}
type responseChecker []*responseMatcher
func (rc *responseChecker) check(resp *Response) error {
for _, matcher := range *rc {
matched, err := matcher.match(resp)
if matched {
return err
}
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
return Error.ToError()
}