-
Notifications
You must be signed in to change notification settings - Fork 11
/
reflect.go
76 lines (67 loc) · 1.58 KB
/
reflect.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 wizard
import (
"reflect"
"strings"
)
// used for shard key in the tag name of struct
const TagName = "shard_key"
// NormalizeValue returns value
// if struct is passed, returns name of the struct
// if pointer is passed, returns non-pointer value
func NormalizeValue(p interface{}) interface{} {
v := toValue(p)
if v.Kind() == reflect.Struct {
return v.Type().String()
}
return v.Interface()
}
func getShardKey(p interface{}) int64 {
v := toValue(p)
if v.Kind() != reflect.Struct {
return 0
}
return getShardKeyFromStruct(p, TagName)
}
// toValue converts any value to reflect.Value
func toValue(p interface{}) reflect.Value {
v := reflect.ValueOf(p)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
return v
}
// toType converts any value to reflect.Type
func toType(p interface{}) reflect.Type {
t := reflect.ValueOf(p).Type()
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
func getShardKeyFromStruct(p interface{}, tagName string) int64 {
t := toType(p)
values := toValue(p)
for i, max := 0, t.NumField(); i < max; i++ {
f := t.Field(i)
if f.PkgPath != "" && !f.Anonymous {
continue
}
tag := parseTag(f, tagName)
// search recursively when `extends` tag
if tag == "extends" {
v := values.Field(i)
return getShardKeyFromStruct(v.Interface(), tagName)
}
if tag != "true" {
continue
}
v := values.Field(i)
return getInt64(v.Interface())
}
return 0
}
// parseTag returns the first tag value of the struct field
func parseTag(f reflect.StructField, tag string) string {
res := strings.Split(f.Tag.Get(tag), ",")
return res[0]
}