-
Notifications
You must be signed in to change notification settings - Fork 4
/
properties.go
55 lines (41 loc) · 1.18 KB
/
properties.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
package xray
import (
"errors"
"strings"
"github.com/oleiade/reflections"
)
// Properties returns the struct fields names list. obj can whether
// be a structure or pointer to structure.
func Properties(obj interface{}) ([]string, error) {
fields, err := reflections.Fields(obj)
if err != nil {
return nil, err
}
return fields, err
}
// PropertiesAsMap returns the properties of an item as a map
func PropertiesAsMap(obj interface{}) (map[string]interface{}, error) {
properties := map[string]interface{}{}
propertyNames, err := Properties(obj)
if err != nil {
return properties, err
}
for _, propertyName := range propertyNames {
propertyValue, _ := Property(obj, propertyName)
properties[propertyName] = propertyValue
}
return properties, nil
}
// Property returns the specific property of obj
func Property(obj interface{}, fieldName string) (interface{}, error) {
fields, err := reflections.Fields(obj)
if err != nil {
return nil, err
}
for _, field := range fields {
if strings.ToLower(field) == strings.ToLower(fieldName) {
return reflections.GetField(obj, field)
}
}
return nil, errors.New("Object doesn't have a property named: " + fieldName)
}