-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag.go
63 lines (48 loc) · 1.12 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
package gowalker
import (
"errors"
"fmt"
"reflect"
"github.com/vkd/gowalker/setter"
)
type Tag string
func (t Tag) Name() string {
return string(t)
}
func (t Tag) Doc(field reflect.StructField, fs Fields) string {
v, _ := t.get(field)
return v
}
func (t Tag) Step(value reflect.Value, field reflect.StructField, fs Fields) (bool, error) {
v, ok := t.get(field)
if !ok {
return false, nil
}
return true, setter.SetString(value, field, v)
}
func (t Tag) get(field reflect.StructField) (string, bool) {
return field.Tag.Lookup(string(t))
}
var ErrRequiredField = errors.New("field is required")
type Required Tag
func (r Required) Name() string {
return Tag(r).Name()
}
func (r Required) Doc(field reflect.StructField, fs Fields) string {
_, ok := Tag(r).get(field)
if ok {
return "*"
}
return ""
}
func (r Required) Step(value reflect.Value, field reflect.StructField, fs Fields) (bool, error) {
t, ok := Tag(r).get(field)
if !ok {
return false, nil
}
switch t {
case "0", "f", "F", "false", "FALSE", "False":
return false, nil
}
return false, fmt.Errorf("%s: %w", field.Name, ErrRequiredField)
}