-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathto_map.go
More file actions
111 lines (89 loc) · 2.38 KB
/
to_map.go
File metadata and controls
111 lines (89 loc) · 2.38 KB
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
package structmapper
import (
"encoding/json"
"fmt"
"reflect"
"time"
)
// StructToStringMap converts a struct to a map[string]string by creating entries in the map
// for each field in the struct. String type values are copied as is. Other types are JSON
// encoded.
// JSON struct tags are consulted for map key names and ommit behaviour.
func StructToStringMap(s interface{}) (map[string]string, error) {
if reflect.TypeOf(s).Kind() != reflect.Ptr || reflect.Indirect(reflect.ValueOf(s)).Kind() != reflect.Struct {
return nil, fmt.Errorf("s must be a pointer to a struct")
}
m := make(map[string]string, 20)
var walkValue func(reflect.Value) error
// Iterate over the given struct and collect values into the map.
// Anonymous fields cause a recursive call to walkValue().
walkValue = func(sv reflect.Value) error {
st := sv.Type()
for i := 0; i < st.NumField(); i++ {
f := sv.Field(i)
ft := st.Field(i)
if ft.PkgPath != "" { // unexported
continue
}
if ft.Anonymous {
if err := walkValue(f); err != nil {
return err
}
continue
}
t, omitEmpty, omit := getJSONTagFromField(ft)
if omit {
continue
}
if omitEmpty && f.Kind() == reflect.Ptr && f.IsNil() {
continue
}
stringValue, err := convertToString(f)
if err != nil {
return err
}
if stringValue == "" && omitEmpty {
continue
}
m[t] = stringValue
}
return nil
}
return m, walkValue(reflect.ValueOf(s).Elem())
}
func convertToString(f reflect.Value) (string, error) {
var stringValue string
if timeString, isT := isTime(f); isT {
stringValue = timeString
} else if f.Kind() == reflect.String {
stringValue = f.String()
} else {
buf, err := json.Marshal(f.Interface())
if err != nil {
return "", fmt.Errorf("json encoding: %w", err)
}
stringValue = string(buf)
}
return stringValue, nil
}
// isTime returns true and the string value if this is a time.Time or *time.Time
// If it's a nil pointer or a zero value time, returns an empty string.
func isTime(f reflect.Value) (string, bool) {
switch f.Kind() {
case reflect.Struct:
if t, ok := f.Interface().(time.Time); ok {
if t.IsZero() {
return "", true
}
return t.Format(time.RFC3339), true
}
case reflect.Ptr:
if t, ok := f.Interface().(*time.Time); ok {
if t == nil {
return "", true
}
return t.Format(time.RFC3339), true
}
}
return "", false
}