-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfor_struct.go
51 lines (38 loc) · 1.22 KB
/
for_struct.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
package validator
import (
"context"
"reflect"
ve "github.com/donatorsky/go-validator/error"
vr "github.com/donatorsky/go-validator/rule"
)
type forStructValidatorOption func(options *validatorOptions) error
func ForStruct(data any, rules RulesMap, options ...forStructValidatorOption) (ve.ErrorsBag, error) {
return ForStructWithContext(context.Background(), data, rules, options...)
}
func ForStructWithContext(ctx context.Context, data any, rules RulesMap, options ...forStructValidatorOption) (ve.ErrorsBag, error) {
data, _ = vr.Dereference(data)
if reflect.TypeOf(data).Kind() != reflect.Struct {
return nil, ve.NotStructTypeError{}
}
opts := &validatorOptions{}
for _, option := range options {
if err := option(opts); err != nil {
return nil, err
}
}
errorsBag := ve.NewErrorsBag()
for field, rules := range rules {
for fieldValue := range newFieldsIterator(field, data) {
if err := applyRules(ctx, data, rules, fieldValue, errorsBag, opts); err != nil {
return nil, err
}
}
}
return errorsBag, nil
}
func ForStructWithDataCollector(collector DataCollector) forStructValidatorOption {
return func(options *validatorOptions) error {
options.dataCollector = collector
return nil
}
}