-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
40 lines (33 loc) · 908 Bytes
/
json.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
package isugata
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
)
// JSONValidateOpt is function type to validate JSON body
type JSONValidateOpt[V any] func(body V) error
// WithJSONValidation decodes JSON body and validates it with opts
func WithJSONValidation[V any](opts ...JSONValidateOpt[V]) ValidateOpt {
return func(res *http.Response) error {
var body V
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
return fmt.Errorf("%w: %w", ErrUndecodableBody, err)
}
for _, o := range opts {
if err := o(body); err != nil {
return err
}
}
return nil
}
}
// JSONEquals validates if JSON body deeply equals to v
func JSONEquals[V comparable](v V) JSONValidateOpt[V] {
return func(body V) error {
if !reflect.DeepEqual(v, body) {
return fmt.Errorf("%w: invalid body content: expected: %v, actual: %v", ErrInvalidBody, v, body)
}
return nil
}
}