This repository has been archived by the owner on Sep 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
reflector.go
315 lines (267 loc) · 8.85 KB
/
reflector.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Package reflector extends standard package reflect with useful utilities.
package reflector
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Converts value to kind. Panics if it can't be done.
type Converter func(value interface{}, kind reflect.Kind) interface{}
// Converter: requires value to be exactly of specified kind.
func NoConvert(value interface{}, kind reflect.Kind) interface{} {
switch kind {
case reflect.Bool:
return value.(bool)
case reflect.Int:
return int64(value.(int))
case reflect.Int8:
return int64(value.(int8))
case reflect.Int16:
return int64(value.(int16))
case reflect.Int32:
return int64(value.(int32))
case reflect.Int64:
return value.(int64)
case reflect.Uint:
return uint64(value.(uint))
case reflect.Uint8:
return uint64(value.(uint8))
case reflect.Uint16:
return uint64(value.(uint16))
case reflect.Uint32:
return uint64(value.(uint32))
case reflect.Uint64:
return value.(uint64)
case reflect.Uintptr:
return uint64(value.(uintptr))
case reflect.Float32:
return float64(value.(float32))
case reflect.Float64:
return value.(float64)
case reflect.String:
return value.(string)
}
panic(fmt.Errorf("NoConvert: can't convert %#v to %s", value, kind))
}
// Converter: uses strconv.Parse* functions.
func Strconv(value interface{}, kind reflect.Kind) (res interface{}) {
e := fmt.Errorf("Strconv: can't convert %#v to %s", value, kind)
s := fmt.Sprint(value)
switch kind {
case reflect.Bool:
res, e = strconv.ParseBool(s)
if e != nil {
panic(e)
}
return
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
res, e = strconv.ParseInt(s, 10, 64)
if e != nil {
panic(e)
}
return
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
res, e = strconv.ParseUint(s, 10, 64)
if e != nil {
panic(e)
}
return
case reflect.Float32, reflect.Float64:
res, e = strconv.ParseFloat(s, 64)
if e != nil {
panic(e)
}
return
case reflect.String:
return s
}
panic(e)
}
// Converts a struct to map.
// First argument is a pointer to struct.
// Second argument is a not-nil map which will be modified.
// Only exported struct fields are used. Pointers will be followed, nils will be present.
// Tag may be used to change mapping between struct field and map key.
// Currently supports bool, ints, uints, floats, strings and pointer to them.
// Panics in case of error.
func StructToMap(StructPointer interface{}, Map map[string]interface{}, tag string) {
structPointerType := reflect.TypeOf(StructPointer)
if structPointerType.Kind() != reflect.Ptr {
panic(fmt.Errorf("StructToMap: expected pointer to struct as first argument, got %s", structPointerType.Kind()))
}
structType := structPointerType.Elem()
if structType.Kind() != reflect.Struct {
panic(fmt.Errorf("StructToMap: expected pointer to struct as first argument, got pointer to %s", structType.Kind()))
}
s := reflect.ValueOf(StructPointer).Elem()
var name string
for i := 0; i < structType.NumField(); i++ {
stf := structType.Field(i)
if stf.PkgPath != "" {
continue
}
name = ""
if tag != "" {
name = strings.Split(stf.Tag.Get(tag), ",")[0]
if name == "-" {
continue
}
}
if name == "" {
name = stf.Name
}
f := s.Field(i)
if f.Kind() == reflect.Ptr {
if f.IsNil() {
Map[name] = nil
continue
}
f = f.Elem()
}
Map[name] = f.Interface()
}
}
// Converts a struct to map. Uses StructToMap().
// First argument is a struct.
// Second argument is a not-nil map which will be modified.
// Only exported struct fields are used. Pointers will be followed, nils will be present.
// Tag may be used to change mapping between struct field and map key.
// Currently supports bool, ints, uints, floats, strings and pointer to them.
// Panics in case of error.
func StructValueToMap(Struct interface{}, Map map[string]interface{}, tag string) {
structType := reflect.TypeOf(Struct)
if structType.Kind() != reflect.Struct {
panic(fmt.Errorf("StructValueToMap: expected struct as first argument, got %s", structType.Kind()))
}
v := reflect.New(reflect.TypeOf(Struct))
v.Elem().Set(reflect.ValueOf(Struct))
StructToMap(v.Interface(), Map, tag)
}
// Converts a slice of structs to a slice of maps. Uses StructValueToMap().
// First argument is a slice of structs.
// Second argument is a pointer to (possibly nil) slice of maps which will be set.
func StructsToMaps(Structs interface{}, Maps *[]map[string]interface{}, tag string) {
sliceType := reflect.TypeOf(Structs)
if sliceType.Kind() != reflect.Slice {
panic(fmt.Errorf("Expected slice of structs as first argument, got %s", sliceType.Kind()))
}
structType := sliceType.Elem()
if structType.Kind() != reflect.Struct {
panic(fmt.Errorf("Expected slice of structs as first argument, got slice of %s", structType.Kind()))
}
structs := reflect.ValueOf(Structs)
l := structs.Len()
maps := reflect.MakeSlice(reflect.TypeOf([]map[string]interface{}{}), 0, l)
for i := 0; i < l; i++ {
m := make(map[string]interface{})
StructValueToMap(structs.Index(i).Interface(), m, tag)
maps = reflect.Append(maps, reflect.ValueOf(m))
}
reflect.ValueOf(Maps).Elem().Set(maps)
}
// Converts a map to struct using converter function.
// First argument is a map.
// Second argument is a not-nil pointer to struct which will be modified.
// Only exported struct fields are set. Omitted or extra values in map are ignored. Pointers will be set.
// Tag may be used to change mapping between struct field and map key.
// Currently supports bool, ints, uints, floats, strings and pointer to them.
// Panics in case of error.
func MapToStruct(Map map[string]interface{}, StructPointer interface{}, converter Converter, tag string) {
structPointerType := reflect.TypeOf(StructPointer)
if structPointerType.Kind() != reflect.Ptr {
panic(fmt.Errorf("MapToStruct: expected pointer to struct as second argument, got %s", structPointerType.Kind()))
}
structType := structPointerType.Elem()
if structType.Kind() != reflect.Struct {
panic(fmt.Errorf("MapToStruct: expected pointer to struct as second argument, got pointer to %s", structType.Kind()))
}
s := reflect.ValueOf(StructPointer).Elem()
var name string
defer func() {
e := recover()
if e == nil {
return
}
panic(fmt.Errorf("MapToStruct, field %s: %s", name, e))
}()
for i := 0; i < structType.NumField(); i++ {
f := s.Field(i)
if !f.CanSet() {
continue
}
stf := structType.Field(i)
name = ""
if tag != "" {
name = strings.Split(stf.Tag.Get(tag), ",")[0]
if name == "-" {
continue
}
}
if name == "" {
name = stf.Name
}
v, ok := Map[name]
if !ok {
continue
}
var fp reflect.Value
kind := f.Kind()
if kind == reflect.Ptr {
t := f.Type().Elem()
kind = t.Kind()
fp = reflect.New(t)
f = fp.Elem()
}
switch kind {
case reflect.Bool:
f.SetBool(converter(v, kind).(bool))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
f.SetInt(converter(v, kind).(int64))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
f.SetUint(converter(v, kind).(uint64))
case reflect.Float32, reflect.Float64:
f.SetFloat(converter(v, kind).(float64))
case reflect.String:
f.SetString(converter(v, kind).(string))
default:
// not implemented
}
if fp.IsValid() {
s.Field(i).Set(fp)
}
}
return
}
// Converts a slice of maps to a slice of structs. Uses MapToStruct().
// First argument is a slice of maps.
// Second argument is a pointer to (possibly nil) slice of structs which will be set.
func MapsToStructs(Maps []map[string]interface{}, SlicePointer interface{}, converter Converter, tag string) {
slicePointerType := reflect.TypeOf(SlicePointer)
if slicePointerType.Kind() != reflect.Ptr {
panic(fmt.Errorf("MapsToStructs: expected pointer to slice of structs as second argument, got %s", slicePointerType.Kind()))
}
sliceType := slicePointerType.Elem()
if sliceType.Kind() != reflect.Slice {
panic(fmt.Errorf("MapsToStructs: expected pointer to slice of structs as second argument, got pointer to %s", sliceType.Kind()))
}
structType := sliceType.Elem()
if structType.Kind() != reflect.Struct {
panic(fmt.Errorf("MapsToStructs: expected pointer to slice of structs as second argument, got pointer to slice of %s", structType.Kind()))
}
slice := reflect.MakeSlice(sliceType, 0, len(Maps))
for _, m := range Maps {
s := reflect.New(structType)
MapToStruct(m, s.Interface(), converter, tag)
slice = reflect.Append(slice, s.Elem())
}
reflect.ValueOf(SlicePointer).Elem().Set(slice)
}
// Variant of MapsToStructs() with relaxed signature.
func MapsToStructs2(Maps []interface{}, SlicePointer interface{}, converter Converter, tag string) {
m := make([]map[string]interface{}, len(Maps))
for index, i := range Maps {
m[index] = i.(map[string]interface{})
}
MapsToStructs(m, SlicePointer, converter, tag)
}