-
Notifications
You must be signed in to change notification settings - Fork 335
/
kv_decoder.go
195 lines (162 loc) · 4.54 KB
/
kv_decoder.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
package types
import (
"fmt"
"reflect"
"strconv"
"strings"
)
type (
// KVDecoder interface for custom decoding logic
KVDecoder interface {
DecodeKV(SettingsKV, string) error
}
)
// DecodeKV converts key-value (SettingsKV) into structs using tags & field names
//
// Supports decoding into all scalar types, can handle nested structures and simple maps (1 dim, string as key)
//
// Example:
// key-value pairs:
// string1: "string"
// number: 42
//
// struct{
// String1 string `kv:"string1`
// Number int
// }
//
func DecodeKV(kv SettingsKV, dst interface{}, pp ...string) (err error) {
valueOf := reflect.ValueOf(dst)
if valueOf.Kind() != reflect.Ptr {
return fmt.Errorf("expecting a pointer, not a value")
}
if valueOf.IsNil() {
return fmt.Errorf("nil pointer passed")
}
var prefix string
if len(pp) > 0 {
// If called with prefix, join string slice + 1 empty string (to ensure tailing dot)
prefix = strings.Join(append(pp, ""), ".")
}
valueOf = valueOf.Elem()
length := valueOf.NumField()
for i := 0; i < length; i++ {
var (
structField = valueOf.Field(i)
tags = make(map[string]bool)
)
if !structField.CanSet() {
continue
}
var (
structFType = valueOf.Type().Field(i)
// whe nwe use name of the struct field directly, remove upper-case from first letter
key = prefix + strings.ToLower(structFType.Name[:1]) + structFType.Name[1:]
tag = structFType.Tag.Get("kv")
tagFlags []string
)
if tag == "-" {
// Skip fields with kv tags equal to "-"
continue
}
if tag != "" {
tagFlags = strings.Split(tag, ",")
if tagFlags[0] != "" {
// key explicitly set via tag, use that!
key = prefix + tagFlags[0]
}
for f := 1; f < len(tagFlags); f++ {
// @todo resolve i18n and other flags...
tags[tagFlags[f]] = true
}
}
var structValue interface{}
if structField.Kind() == reflect.Ptr {
structValue = structField.Interface()
} else {
structValue = structField.Addr().Interface()
}
// Handle custom KVDecoder
if decodeMethod := reflect.ValueOf(structValue).MethodByName("DecodeKV"); decodeMethod.IsValid() {
if decode, ok := decodeMethod.Interface().(func(SettingsKV, string) error); !ok {
panic("invalid DecodeKV() function signature")
} else if err = decode(kv, key); err != nil {
return fmt.Errorf("cannot decode settings for %q: %w", key, err)
} else {
continue
}
}
if !tags["final"] {
// Handles structs
//
// It calls DecodeKV recursively
if structField.Kind() == reflect.Struct {
if err = DecodeKV(kv.Filter(key), structValue, key); err != nil {
return err
}
continue
}
// Handles map values
if structField.Kind() == reflect.Map {
if structField.IsNil() {
// allocate new map
structField.Set(reflect.MakeMap(structField.Type()))
}
// cut SettingsKV key prefix and use the rest for the map key
for k, val := range kv.CutPrefix(key + ".") {
mapValue := reflect.New(structField.Type().Elem())
err = val.Unmarshal(mapValue.Interface())
if err != nil {
return fmt.Errorf("cannot decode JSON into map for key %q: %w", key, err)
}
structField.SetMapIndex(reflect.ValueOf(k), mapValue.Elem())
}
continue
}
}
// Native type
if val, ok := kv[key]; ok {
// Take care of null values
if val == nil || val.String() == "null" {
switch structFType.Type.Kind() {
case reflect.String:
structField.SetString("")
case reflect.Int, reflect.Int32, reflect.Int64:
structField.SetInt(0)
case reflect.Uint, reflect.Uint32, reflect.Uint64:
structField.SetUint(0)
case reflect.Float32, reflect.Float64:
structField.SetFloat(0)
}
continue
}
if err = val.Unmarshal(structField.Addr().Interface()); err != nil {
// Try to get numbers encoded as strings...
var tmp interface{}
if err = val.Unmarshal(&tmp); err != nil {
return fmt.Errorf("could not decode JSON for key %q: %w", key, err)
}
var cnv, is = tmp.(string)
if !is {
// give up
continue
}
switch structFType.Type.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64:
if num, err := strconv.ParseInt(cnv, 10, 64); err == nil {
structField.SetInt(num)
}
case reflect.Uint, reflect.Uint32, reflect.Uint64:
if num, err := strconv.ParseUint(cnv, 10, 64); err == nil {
structField.SetUint(num)
}
case reflect.Float32, reflect.Float64:
if num, err := strconv.ParseFloat(cnv, 64); err == nil {
structField.SetFloat(num)
}
}
}
}
}
return
}