-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag.go
64 lines (54 loc) · 1.42 KB
/
tag.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
61
62
63
64
package valis
import (
"fmt"
"sync"
"github.com/soranoba/valis/code"
)
type (
// FieldTagHandler is an interface to be registered in FieldTagRule.
// It has a role in creating a Rule from the TagValue.
FieldTagHandler interface {
ParseTagValue(tagValue string) ([]Rule, error)
}
)
type (
fieldTagRule struct {
key string
tagHandler FieldTagHandler
lock *sync.RWMutex
cache map[string][]Rule
}
)
// NewFieldTagRule returns a new rule related to the field tag.
// The rule verifies the value when it is a field value and has the specified tag.
func NewFieldTagRule(key string, tagHandler FieldTagHandler) *fieldTagRule {
return &fieldTagRule{key: key, tagHandler: tagHandler, lock: &sync.RWMutex{}, cache: map[string][]Rule{}}
}
func (r *fieldTagRule) Validate(validator *Validator, value interface{}) {
loc := validator.Location()
if loc.Kind() != LocationKindField {
validator.ErrorCollector().Add(loc, NewError(code.NotStruct, value))
return
}
field := loc.Field()
tag, ok := field.Tag.Lookup(r.key)
if !ok {
return
}
r.lock.RLock()
rules, ok := r.cache[tag]
r.lock.RUnlock()
if !ok {
var err error
rules, err = r.tagHandler.ParseTagValue(tag)
if err != nil {
panic(fmt.Sprintf("%s (key = %s, path = %s)", err.Error(), r.key, field.PkgPath))
}
r.lock.Lock()
r.cache[tag] = rules
r.lock.Unlock()
}
for _, rule := range rules {
rule.Validate(validator, value)
}
}