-
Notifications
You must be signed in to change notification settings - Fork 0
/
structs.go
60 lines (50 loc) · 1.55 KB
/
structs.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
package structs
import (
"fmt"
)
// Struct holds the structure to be validated and the rules to validate it with
type Struct struct {
structure any
ruleFuncs map[string]RuleFunc
validationMessageTag string
tags []string
}
var DefaultTags = []string{"arg", "short", "json", "yaml"}
func New(structure any, rules map[string]RuleFunc, tags ...string) *Struct {
return &Struct{
structure: structure,
validationMessageTag: validationTag,
ruleFuncs: rules,
tags: tags,
}
}
func NewWithValidation(structure any, rules map[string]RuleFunc, validationTag string, tags ...string) *Struct {
return &Struct{
structure: structure,
validationMessageTag: validationTag,
ruleFuncs: rules,
tags: tags,
}
}
func (m *Struct) Validate(inputs map[string]any) (map[string][]string, error) {
structFields, err := GetStructFields(m.structure, nil)
if err != nil {
return nil, fmt.Errorf("error getting struct fields for validation: %w", err)
}
errors, err := ValidateStructFields(m.ruleFuncs, structFields, inputs, m.validationMessageTag, m.tags...)
if err != nil {
return nil, fmt.Errorf("error validating struct with inputs: %w", err)
}
return errors, nil
}
func (m *Struct) Set(inputs map[string]any) error {
err := SetStructFields(m.structure, Settings{
TagOrder: m.tags,
AllowEnvOverride: false,
AllowTagOverride: false,
}, inputs)
if err != nil {
return fmt.Errorf("error setting struct fields: %w", err)
}
return nil
}