-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_field.go
48 lines (39 loc) · 1.01 KB
/
json_field.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 isugata
import (
"fmt"
"reflect"
)
// JSONFieldValidate validates JSON filed with opts
func JSONFieldValidate[V, F any](name string, opts ...JSONValidateOpt[F]) JSONValidateOpt[V] {
return func(body V) error {
bodyV := reflect.ValueOf(body)
fieldI := bodyV.FieldByName(name).Interface()
field, ok := fieldI.(F)
if !ok {
return fmt.Errorf("%w: unable to get field %s", ErrInvalidBody, name)
}
for _, o := range opts {
if err := o(field); err != nil {
return err
}
}
return nil
}
}
// JSONArrayFieldValidate validates JSON array filed with opts
func JSONArrayFieldValidate[V, F any](name string, opts ...JSONArrayValidateOpt[F]) JSONValidateOpt[V] {
return func(body V) error {
bodyRv := reflect.ValueOf(body)
fieldI := bodyRv.FieldByName(name).Interface()
field, ok := fieldI.([]F)
if !ok {
return fmt.Errorf("%w: unable to get field %s", ErrInvalidBody, name)
}
for _, o := range opts {
if err := o(field); err != nil {
return err
}
}
return nil
}
}