-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfield.go
119 lines (100 loc) · 2.16 KB
/
field.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package validator
import (
"fmt"
"reflect"
)
type (
// ParentField represents a parent of Field.
ParentField struct {
origin reflect.Value
}
// Field represents a value.
Field struct {
name string
origin reflect.Value
current reflect.Value
parent ParentField
}
)
const (
fieldNameDelim = "."
)
func newFieldWithParent(name string, origin, current reflect.Value, parent Field) Field {
if name == "" {
name = parent.name
} else if parent.name != "" {
if name[0] == '[' {
name = parent.name + name
} else {
name = parent.name + fieldNameDelim + name
}
}
return Field{
name: name,
origin: origin,
current: current,
parent: ParentField{origin: parent.origin},
}
}
// Name is a field name. e.g. Foo.Bar.Value
func (f Field) Name() string {
return f.name
}
// Interface returns an interface{}
func (f Field) Interface() interface{} {
return f.origin.Interface()
}
// Value returns a current field value.
func (f Field) Value() reflect.Value {
return f.current
}
// Parent returns a parent field.
func (f Field) Parent() ParentField {
return f.parent
}
// ShortString returns a string with 32 characters or more omitted.
func (f Field) ShortString() string {
const maxSize = 32
s := f.String()
if len(s) > maxSize {
return s[:maxSize] + "..."
}
return s
}
// String returns a string.
func (f Field) String() string {
val := f.current
switch val.Kind() {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64:
return fmt.Sprint(val)
case reflect.String:
return val.String()
case reflect.Struct:
return val.Type().Name()
case reflect.Map:
return "<Map>"
case reflect.Slice, reflect.Array:
return "<Array>"
case reflect.Interface:
if val.IsNil() {
return "<nil>"
}
return "<Interface>"
case reflect.Ptr:
if val.IsNil() {
return "<nil>"
}
return "<Ptr>"
}
return "<Unknown>"
}
// Interface returns an interface{}
func (f ParentField) Interface() interface{} {
if f.origin.IsValid() {
return f.origin.Interface()
}
return nil
}