-
Notifications
You must be signed in to change notification settings - Fork 9
/
idhandler.go
128 lines (118 loc) · 2.64 KB
/
idhandler.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
120
121
122
123
124
125
126
127
128
package toolkit
import (
"errors"
"reflect"
"strings"
)
func IdInfo(i interface{}) (idfield string, id interface{}) {
//_ = "breakpoint"
idFields := []interface{}{"_id", "ID", "Id", "id"}
rv := reflect.ValueOf(i)
//-- get key
//found := false
if rv.Kind() == reflect.Map {
mapkeys := rv.MapKeys()
for _, mapkey := range mapkeys {
idkey := mapkey.String()
if HasMember(idFields, idkey) {
idValue := rv.MapIndex(mapkey)
if idValue.IsValid() {
idfield = idkey
id = idValue.Interface()
return
}
}
}
} else if rv.Kind() == reflect.Struct {
for _, idkey := range idFields {
idValue := rv.FieldByName(idkey.(string))
if idValue.IsValid() {
idfield = idkey.(string)
id = idValue.Interface()
return
}
}
} else if rv.Kind() == reflect.Ptr {
elem := rv.Elem()
for _, idkey := range idFields {
idValue := elem.FieldByName(idkey.(string))
if idValue.IsValid() {
idfield = idkey.(string)
id = idValue.Interface()
return
}
}
} else {
//_ = "breakpoint"
//fmt.Printf("Kind: %s \n", rv.Kind().String())
}
if idfield == "" {
var elem reflect.Value
if rv.Kind() == reflect.Struct {
elem = rv
} else if rv.Kind() == reflect.Ptr {
elem = rv.Elem()
}
if elem.IsValid() {
fc := elem.NumField()
ft := elem.Type()
for fi := 0; fi < fc; fi++ {
idValue := elem.FieldByIndex([]int{fi})
if idValue.IsValid() {
tags := strings.Split(ft.Field(fi).Tag.Get("bson"), ",")
if len(tags) > 0 {
fieldname := ft.Field(fi).Name
if HasMember(tags, "_id") {
idfield = fieldname
}
}
return
}
}
}
}
return
}
func Id(i interface{}) interface{} {
f, i := IdInfo(i)
if f == "" {
return nil
}
return i
}
func IdField(i interface{}) string {
f, _ := IdInfo(i)
return f
}
func SetValue(rv *reflect.Value, value interface{}) error {
v := reflect.ValueOf(value)
rv.Set(v)
return nil
}
func SetId(i interface{}, id interface{}) error {
idfield := IdField(i)
if idfield == "" {
return errors.New("toolkit.SetId: No ID field")
}
rv := reflect.ValueOf(i)
//-- get key
//found := false
if rv.Kind() == reflect.Map {
mapkeys := rv.MapKeys()
for _, mapkey := range mapkeys {
idkey := mapkey.String()
if idkey == idfield {
mapvalue := rv.MapIndex(mapkey)
return SetValue(&mapvalue, id)
}
}
} else if rv.Kind() == reflect.Struct {
idValue := rv.FieldByName(idfield)
return SetValue(&idValue, id)
} else if rv.Kind() == reflect.Ptr {
elem := rv.Elem()
idValue := elem.FieldByName(idfield)
return SetValue(&idValue, id)
}
return errors.New("toolkit.SetID: Invalid type " + rv.Type().String())
}