-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbody_json_query_exists.go
45 lines (36 loc) · 984 Bytes
/
body_json_query_exists.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
package check
import (
"context"
"fmt"
"github.com/tidwall/gjson"
"net/http"
)
// JSONQueryValueMissingError is returned when a check fails.
type JSONQueryValueMissingError struct {
// Query is the JSON query.
Query string
}
// Error returns an error string.
func (e *JSONQueryValueMissingError) Error() string {
return fmt.Sprintf("value at %v is missing", e.Query)
}
// BodyJSONQueryExistsChecker queries the http response body JSON using `Query` and ensures a value exists there
type BodyJSONQueryExistsChecker struct {
Query string
DataID string
}
// Check performs the BodyJSONQueryExists check
func (c *BodyJSONQueryExistsChecker) Check(ctx context.Context, response *http.Response) error {
body, err := readResponseBody(response)
if err != nil {
return err
}
j := gjson.ParseBytes(body)
r := j.Get(c.Query)
if !r.Exists() {
return &JSONQueryValueMissingError{
Query: c.Query,
}
}
return ContextWithOptionalDataID(ctx, c.DataID, r.Value())
}