-
Notifications
You must be signed in to change notification settings - Fork 7
/
decoder.go
543 lines (529 loc) · 15.2 KB
/
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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Package decoder provide a way to decode credentials from a service to a structure
// It provides a cloud tag to help user match the correct credentials
//
// This is what you can pass as a structure:
//
// // Name is key of a service credentials, decoder will look at any matching credentials which have the key name and will pass the value of this credentials
// Name string `cloud:"name"` // note: by default if you don't provide a cloud tag the key will be the field name in snake_case
// Uri decoder.ServiceUri // ServiceUri is a special type. Decoder will expect an uri as a value and will give a ServiceUri
// User string `cloud:".*user.*,regex"` // by passing `regex` in cloud tag it will say to decoder that the expected key must be match the regex
// Password string `cloud:".*user.*,regex" cloud-default:"apassword"` // by passing a tag named `cloud-default` decoder will understand that if the key is not found it must fill the field with this value
// Aslice []string `cloud:"aslice" cloud-default:"value1,value2"` // you can also pass a slice
// }
package decoder
import (
"encoding/json"
"fmt"
"github.com/azer/snakecase"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
)
const (
identifier = "cloud"
identifier_default_value = "cloud-default"
regexTag = "regex"
defaultTag = "default"
skipTag = "-"
)
type Tag struct {
Name string
Skip bool
IsRegex bool
DefaultValue string
}
type ServiceUri struct {
Username string
Password string
Scheme string
Host string
Name string
Query []QueryUri
RawQuery string
Port int
}
type QueryUri struct {
Key string
Value string
}
// Unmarshaler This interface may be implemented by types to customize their
// behavior when being unmarshalled from a Map cloud. The UnmarshalCloud
// method receives a function that may be called to unmarshal the original
// value into a field or variable. It is safe to call the unmarshal
// function parameter more than once if necessary.
type Unmarshaler interface {
UnmarshalCloud(data interface{}) error
}
// UnmarshalToValue Decode a map of credentials into a reflected Value
func UnmarshalToValue(serviceCredentials map[string]interface{}, ps reflect.Value, noDefaultVal bool) error {
v := ps
if ps.Kind() == reflect.Ptr {
v = ps.Elem()
}
t := v.Type()
var err error
for index := 0; index < v.NumField(); index++ {
vField := v.Field(index)
tField := t.Field(index)
if !vField.CanAddr() || !vField.CanSet() {
continue
}
tag := parseInTag(tField.Tag.Get(identifier), tField.Name)
if tag.Skip {
continue
}
key := tag.Name
if tag.IsRegex {
key = getKeyFromRegex(serviceCredentials, tag.Name)
}
defaultValueFromTag := tField.Tag.Get(identifier_default_value)
if defaultValueFromTag != "" {
tag.DefaultValue = defaultValueFromTag
}
defaultValue := tag.DefaultValue
if noDefaultVal {
defaultValue = ""
}
data := retrieveFinalData(vField.Type(), serviceCredentials, key, defaultValue)
if data == nil {
continue
}
dataKind := reflect.TypeOf(data).Kind()
if dataKind == reflect.String && reflect.TypeOf(data) != reflect.TypeOf(json.Number("")) {
data, err = convertStringValue(data.(string), vField)
if err != nil {
return NewErrDecode(fmt.Sprintf(
"Error on field '%s' when trying to convert value '%s' in '%s': %s",
tField.Name,
defaultValue,
vField.Kind().String(),
err.Error(),
))
}
}
err = affect(data, vField, noDefaultVal)
if err != nil {
return NewErrDecode(fmt.Sprintf("Error on field '%s': %s", tField.Name, err.Error()))
}
}
return nil
}
// Unmarshal Decode a map of credentials into a structure
func Unmarshal(serviceCredentials map[string]interface{}, obj interface{}) error {
ps := reflect.ValueOf(obj)
return UnmarshalToValue(serviceCredentials, ps, false)
}
// UnmarshalNoDefault Decode a map of credentials into a structure without default values
func UnmarshalNoDefault(serviceCredentials map[string]interface{}, obj interface{}) error {
ps := reflect.ValueOf(obj)
return UnmarshalToValue(serviceCredentials, ps, true)
}
func isUnmarshaler(vField reflect.Value) bool {
if vField.Type().Kind() != reflect.Ptr {
return false
}
ptrVal := vField
if vField.IsNil() {
ptrVal = reflect.New(vField.Type().Elem())
}
_, ok := ptrVal.Interface().(Unmarshaler)
return ok
}
func parseForInt(data interface{}, vField reflect.Value) interface{} {
if reflect.ValueOf(data).Kind() != reflect.Float32 &&
reflect.ValueOf(data).Kind() != reflect.Float64 &&
reflect.TypeOf(data) != reflect.TypeOf(json.Number("")) {
return data
}
if reflect.TypeOf(data) == reflect.TypeOf(json.Number("")) {
jsonInt, err := data.(json.Number).Int64()
if err != nil {
panic(err)
}
val, _ := convertStringValue(fmt.Sprintf("%d", jsonInt), vField)
return val
}
if reflect.ValueOf(data).Kind() == reflect.Float32 {
val, _ := convertStringValue(fmt.Sprintf("%.0f", data.(float32)), vField)
return val
}
val, _ := convertStringValue(fmt.Sprintf("%.0f", data.(float64)), vField)
return val
}
func parseForFloat(data interface{}, vField reflect.Value) float64 {
if reflect.TypeOf(data) == reflect.TypeOf(json.Number("")) {
floatData, err := data.(json.Number).Float64()
if err != nil {
panic(err)
}
return floatData
}
if vField.Kind() == reflect.Float32 {
return float64(data.(float32))
}
return data.(float64)
}
func affect(data interface{}, vField reflect.Value, noDefaultVal bool) error {
switch vField.Kind() {
case reflect.String:
vField.SetString(data.(string))
case reflect.Int:
vField.SetInt(int64(parseForInt(data, vField).(int)))
case reflect.Int8:
vField.SetInt(int64(parseForInt(data, vField).(int8)))
case reflect.Int16:
vField.SetInt(int64(parseForInt(data, vField).(int16)))
case reflect.Int32:
vField.SetInt(int64(parseForInt(data, vField).(int32)))
case reflect.Int64:
vField.SetInt(parseForInt(data, vField).(int64))
case reflect.Uint:
vField.SetUint(uint64(parseForInt(data, vField).(uint)))
case reflect.Uint8:
vField.SetUint(uint64(parseForInt(data, vField).(uint8)))
case reflect.Uint16:
vField.SetUint(uint64(parseForInt(data, vField).(uint16)))
case reflect.Uint32:
vField.SetUint(uint64(parseForInt(data, vField).(uint32)))
case reflect.Uint64:
vField.SetUint(parseForInt(data, vField).(uint64))
case reflect.Slice:
if vField.IsNil() {
vField.Set(reflect.MakeSlice(reflect.SliceOf(vField.Type().Elem()), 0, 0))
}
if reflect.ValueOf(data).Kind() != reflect.Slice {
return fmt.Errorf("type '%s' have not receive a slice", vField.String())
}
dataValue := reflect.ValueOf(data)
if dataValue.Type().Kind() == reflect.Interface {
dataValue = dataValue.Elem()
}
for i := 0; i < dataValue.Len(); i++ {
var newElem reflect.Value
dataValueElem := dataValue.Index(i)
if dataValueElem.Type().Kind() == reflect.Interface {
dataValueElem = dataValueElem.Elem()
}
newElem = dataValueElem
if vField.Type().Elem().Kind() == reflect.Ptr {
newElem = reflect.New(vField.Type().Elem().Elem())
if isUnmarshaler(newElem) {
err := newElem.Interface().(Unmarshaler).UnmarshalCloud(dataValueElem.Interface())
if err != nil {
return err
}
} else {
err := affect(dataValueElem.Interface(), newElem.Elem(), noDefaultVal)
if err != nil {
return err
}
}
} else if dataValueElem.Type() == reflect.TypeOf(make(map[string]interface{})) {
newElem = reflect.New(vField.Type().Elem())
err := UnmarshalToValue(dataValueElem.Interface().(map[string]interface{}), newElem, noDefaultVal)
if err != nil {
return err
}
newElem = newElem.Elem()
}
vField.Set(reflect.Append(vField, newElem))
}
case reflect.Interface:
vField.Set(reflect.ValueOf(data))
case reflect.Bool:
vField.SetBool(data.(bool))
case reflect.Float32:
vField.SetFloat(parseForFloat(data, vField))
case reflect.Float64:
vField.SetFloat(parseForFloat(data, vField))
case reflect.Ptr:
if vField.IsNil() {
vField.Set(reflect.New(vField.Type().Elem()))
}
if isUnmarshaler(vField) {
err := vField.Interface().(Unmarshaler).UnmarshalCloud(data)
if err != nil {
return err
}
break
}
err := affect(data, vField.Elem(), noDefaultVal)
if err != nil {
return err
}
default:
servUriType := reflect.TypeOf(ServiceUri{})
if vField.Type() != servUriType && reflect.TypeOf(data) != reflect.TypeOf(make(map[string]interface{})) {
return NewErrTypeNotSupported(vField)
}
if vField.Kind() == reflect.Map &&
reflect.TypeOf(data) == reflect.TypeOf(make(map[string]interface{})) {
return unmarshalUntypedMap(data.(map[string]interface{}), vField, noDefaultVal)
}
if reflect.TypeOf(data) == reflect.TypeOf(make(map[string]interface{})) {
return UnmarshalToValue(data.(map[string]interface{}), vField, noDefaultVal)
}
serviceUrl, err := url.Parse(data.(string))
if err != nil {
return err
}
serviceUri := urlToServiceUri(serviceUrl)
vField.Set(reflect.ValueOf(serviceUri))
}
return nil
}
func unmarshalUntypedMap(data map[string]interface{}, vField reflect.Value, noDefaultVal bool) error {
if vField.Type() == reflect.TypeOf(make(map[string]interface{})) {
vField.Set(reflect.ValueOf(data))
return nil
}
if vField.IsNil() {
vField.Set(reflect.MakeMap(vField.Type()))
}
for name, val := range data {
if reflect.TypeOf(val) != reflect.TypeOf(make(map[string]interface{})) {
vField.SetMapIndex(reflect.ValueOf(name), reflect.ValueOf(val))
continue
}
typeElem := vField.Type().Elem()
if typeElem.Kind() == reflect.Ptr {
typeElem = typeElem.Elem()
}
newElem := reflect.New(typeElem)
err := UnmarshalToValue(val.(map[string]interface{}), newElem, noDefaultVal)
if err != nil {
return err
}
if vField.Type().Elem().Kind() != reflect.Ptr {
newElem = newElem.Elem()
}
vField.SetMapIndex(reflect.ValueOf(name), newElem)
}
return nil
}
func parseInTag(tag, fieldName string) Tag {
if tag == "" {
return Tag{
Name: snakecase.SnakeCase(fieldName),
}
}
tag = strings.TrimSpace(tag)
splitedTag := strings.Split(tag, ",")
name := splitedTag[0]
skipped := false
if name == skipTag {
skipped = true
}
if name == "" {
name = snakecase.SnakeCase(fieldName)
}
return Tag{
Name: name,
Skip: skipped,
IsRegex: hasRegexTag(splitedTag[1:]),
DefaultValue: getDefaultTagValue(splitedTag[1:]),
}
}
func hasRegexTag(tags []string) bool {
for _, tag := range tags {
if tag == regexTag {
return true
}
}
return false
}
func getDefaultTagValue(tags []string) string {
for _, tag := range tags {
splitedDefTag := strings.Split(tag, "=")
if len(splitedDefTag) < 2 || splitedDefTag[0] != defaultTag {
continue
}
return strings.TrimSpace(strings.Join(splitedDefTag[1:], "="))
}
return ""
}
func retrieveFinalData(typeOf reflect.Type, serviceCredentials map[string]interface{}, key, defaultValue string) interface{} {
valueExists := isValueExists(serviceCredentials, key)
if !valueExists &&
defaultValue == "" &&
typeOf.Kind() != reflect.Struct {
return nil
}
if valueExists {
return serviceCredentials[key]
}
if !valueExists && defaultValue != "" {
return defaultValue
}
if !valueExists && typeOf.Kind() == reflect.Struct && reflect.TypeOf(ServiceUri{}) == typeOf {
return make(map[string]interface{})
}
if !valueExists && typeOf.Kind() == reflect.Struct {
return serviceCredentials
}
return nil
}
func isValueExists(serviceCredentials map[string]interface{}, key string) bool {
if key == "" {
return false
}
_, ok := serviceCredentials[key]
return ok
}
func match(matcher, content string) bool {
regex, err := regexp.Compile("(?i)^" + matcher + "$")
if err != nil {
return false
}
return regex.MatchString(content)
}
func getKeyFromRegex(serviceCredentials map[string]interface{}, regexKey string) string {
for key := range serviceCredentials {
if match(regexKey, key) {
return key
}
}
return ""
}
func urlToServiceUri(url *url.URL) ServiceUri {
username := ""
password := ""
if url.User != nil {
if url.User.Username() != "" {
username = url.User.Username()
}
_, hasPassword := url.User.Password()
if hasPassword {
password, _ = url.User.Password()
}
}
queries := make([]QueryUri, 0)
for key, value := range url.Query() {
queries = append(queries, QueryUri{
Key: key,
Value: value[0],
})
}
host := url.Host
port := 0
splitedHost := strings.Split(host, ":")
if len(splitedHost) == 2 {
host = splitedHost[0]
port, _ = strconv.Atoi(splitedHost[1])
}
return ServiceUri{
Scheme: url.Scheme,
Username: username,
Password: password,
Host: host,
Port: port,
Name: strings.TrimPrefix(url.Path, "/"),
Query: queries,
RawQuery: url.RawQuery,
}
}
func convertStringValue(defVal string, vField reflect.Value) (interface{}, error) {
switch vField.Kind() {
case reflect.String:
return defVal, nil
case reflect.Interface:
return defVal, nil
case reflect.Int:
return strconv.Atoi(defVal)
case reflect.Int8:
val, err := strconv.ParseInt(defVal, 10, 8)
if err != nil {
return "", err
}
return int8(val), nil
case reflect.Int16:
val, err := strconv.ParseInt(defVal, 10, 16)
if err != nil {
return "", err
}
return int16(val), nil
case reflect.Int32:
val, err := strconv.ParseInt(defVal, 10, 32)
if err != nil {
return "", err
}
return int32(val), nil
case reflect.Int64:
val, err := strconv.ParseInt(defVal, 10, 64)
if err != nil {
return "", err
}
return val, nil
case reflect.Uint:
val, err := strconv.ParseUint(defVal, 10, strconv.IntSize)
if err != nil {
return "", err
}
return uint(val), nil
case reflect.Uint8:
val, err := strconv.ParseUint(defVal, 10, 8)
if err != nil {
return "", err
}
return uint8(val), nil
case reflect.Uint16:
val, err := strconv.ParseUint(defVal, 10, 16)
if err != nil {
return "", err
}
return uint16(val), nil
case reflect.Uint32:
val, err := strconv.ParseUint(defVal, 10, 32)
if err != nil {
return "", err
}
return uint32(val), nil
case reflect.Uint64:
val, err := strconv.ParseUint(defVal, 10, 64)
if err != nil {
return "", err
}
return val, nil
case reflect.Bool:
return strconv.ParseBool(defVal)
case reflect.Float32:
val, err := strconv.ParseFloat(defVal, 32)
if err != nil {
return "", err
}
return float32(val), nil
case reflect.Float64:
val, err := strconv.ParseFloat(defVal, 64)
if err != nil {
return "", err
}
return float64(val), nil
case reflect.Slice:
finalField := reflect.MakeSlice(reflect.SliceOf(vField.Type().Elem()), 0, 0)
defValSlice := strings.Split(defVal, ",")
for _, aDefVal := range defValSlice {
finDefVal, err := convertStringValue(strings.TrimSpace(aDefVal), reflect.New(vField.Type().Elem()))
if err != nil {
return "", err
}
finalField = reflect.Append(finalField, reflect.ValueOf(finDefVal))
}
return finalField.Interface(), nil
case reflect.Ptr:
if vField.IsNil() {
vField.Set(reflect.New(vField.Type().Elem()))
}
if isUnmarshaler(vField) {
return defVal, nil
}
return convertStringValue(defVal, vField.Elem())
default:
servUriType := reflect.TypeOf(ServiceUri{})
if vField.Type() != servUriType {
return "", NewErrTypeNotSupported(vField)
}
return defVal, nil
}
}