-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfield_int_duration.go
81 lines (71 loc) · 1.34 KB
/
field_int_duration.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package flagx
import (
"flag"
"reflect"
"time"
)
func init() {
IntFieldHook.Append(&Hook{(*DurationField)(nil).Fit, NewDurationField})
}
type DurationField struct {
f *Field
defval time.Duration
Max *time.Duration
Min *time.Duration
}
func NewDurationField(f *Field) Fielder {
df := &DurationField{
f: f,
}
return df
}
func (d *DurationField) Init() (err error) {
if d.f.DefVal != "" {
d.defval, err = time.ParseDuration(d.f.DefVal)
if err != nil {
return err
}
}
return nil
}
func (d *DurationField) BindOpt(key, value string) error {
switch key {
case KEY_MAX, KEY_MIN:
v, err := time.ParseDuration(value)
if err != nil {
return err
}
if key == KEY_MAX {
d.Max = &v
} else {
d.Min = &v
}
default:
return ErrOptMissHandler.Format(key, d.f.Name)
}
return nil
}
func (d *DurationField) BindFlag(fs *flag.FlagSet) {
ins := d.f.Instance().(*time.Duration)
fs.DurationVar(ins, d.f.FlagName(), d.defval, d.f.Usage)
}
func (d *DurationField) Fit(t reflect.Type) bool {
return t.AssignableTo(TypeDuration)
}
func (d *DurationField) Default() interface{} {
return d.defval
}
func (d *DurationField) AfterParse() error {
ptr := d.f.Instance().(*time.Duration)
if d.Min != nil {
if *ptr < *d.Min {
*ptr = *d.Min
}
}
if d.Max != nil {
if *ptr > *d.Max {
*ptr = *d.Max
}
}
return nil
}