forked from thoas/go-funk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retrieve.go
75 lines (54 loc) · 1.4 KB
/
retrieve.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
package funk
import (
"reflect"
"strings"
)
// Get retrieves the value at path of struct(s).
func Get(out interface{}, path string) interface{} {
result := get(reflect.ValueOf(out), path)
if result.Kind() != reflect.Invalid {
return result.Interface()
}
return nil
}
func get(value reflect.Value, path string) reflect.Value {
if value.Kind() == reflect.Slice || value.Kind() == reflect.Array {
var resultSlice reflect.Value
length := value.Len()
for i := 0; i < length; i++ {
item := value.Index(i)
resultValue := get(item, path)
if resultValue.Kind() == reflect.Invalid {
continue
}
resultType := resultValue.Type()
if resultSlice.Kind() == reflect.Invalid {
resultType := reflect.SliceOf(resultType)
resultSlice = reflect.MakeSlice(resultType, 0, 0)
}
resultSlice = reflect.Append(resultSlice, resultValue)
}
// if the result is a slice of a slice, we need to flatten it
if resultSlice.Type().Elem().Kind() == reflect.Slice {
return flattenDeep(resultSlice)
}
return resultSlice
}
parts := strings.Split(path, ".")
for _, part := range parts {
value = redirectValue(value)
kind := value.Kind()
if kind == reflect.Invalid {
continue
}
if kind == reflect.Struct {
value = value.FieldByName(part)
continue
}
if kind == reflect.Slice || kind == reflect.Array {
value = get(value, part)
continue
}
}
return value
}