-
Notifications
You must be signed in to change notification settings - Fork 0
/
structmap.go
76 lines (62 loc) · 1.42 KB
/
structmap.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
package structmap
import (
"errors"
"reflect"
"strings"
)
var Tag = "map"
var TagPref = []string{Tag}
var (
ErrNonStruct = errors.New("not a struct")
ErrNonStringKeyMap = errors.New("only supports maps with string as key")
ErrNotPtr = errors.New("not a pointer")
)
// unpack an interface and get the underlying value and type. Enters infinite loop if i is a pointer to itself.
func unpackInterface(i interface{}) (v reflect.Value, t reflect.Type) {
v = reflect.ValueOf(i)
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
if v.IsValid() {
t = v.Type()
}
return
}
func updateMap(dst map[string]interface{}, src map[string]interface{}) {
for k, v := range src {
dst[k] = v
}
}
func scanTag(f reflect.StructField) (name string, opts map[string]interface{}) {
tags := f.Tag
opts = make(map[string]interface{})
for _, tagName := range TagPref {
_name, _opts := parseTag(tags.Get(tagName))
if name == "" && _name != "" {
name = _name
}
updateMap(opts, _opts)
}
if name == "" {
name = f.Name
}
return
}
func parseTag(tag string) (name string, opts map[string]interface{}) {
opts = make(map[string]interface{})
if tag == "" {
return
}
parts := strings.Split(tag, ",")
name = parts[0]
for _, part := range parts[1:] {
kv := strings.SplitN(part, ":", 2)
if len(kv) == 1 {
opts[kv[0]] = true
}
if len(kv) == 2 {
opts[kv[0]] = kv[1]
}
}
return
}