-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
92 lines (77 loc) · 1.8 KB
/
decoder.go
File metadata and controls
92 lines (77 loc) · 1.8 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
package utils
import (
"fmt"
"github.com/mitchellh/mapstructure"
"net/url"
"reflect"
"strings"
"time"
)
func Decoder(result any) (*mapstructure.Decoder, error) {
config := &mapstructure.DecoderConfig{
Result: result,
}
ConfigureDecoder(config)
return mapstructure.NewDecoder(config)
}
func ConfigureDecoder(config *mapstructure.DecoderConfig) {
config.TagName = "json"
config.WeaklyTypedInput = false
config.DecodeHook = mapstructure.ComposeDecodeHookFunc(urlDecoder(), timeDecoder(), stringToSlice())
}
func urlDecoder() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if t != reflect.TypeOf(url.URL{}) {
return data, nil
}
var (
str string
err error
ok bool
u *url.URL
)
if str, ok = data.(string); !ok {
return nil, fmt.Errorf("cannot map %v", reflect.TypeOf(data))
}
if u, err = url.Parse(str); err != nil {
return nil, err
}
return u, nil
}
}
func timeDecoder() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if t != reflect.TypeOf(time.Time{}) {
return data, nil
}
switch f.Kind() {
case reflect.String:
return time.Parse(time.RFC3339, data.(string))
case reflect.Float64:
return time.Unix(0, int64(data.(float64))*int64(time.Millisecond)), nil
case reflect.Int64:
return time.Unix(0, data.(int64)*int64(time.Millisecond)), nil
default:
return data, nil
}
}
}
func stringToSlice() mapstructure.DecodeHookFunc {
return func(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
if f != reflect.String || t != reflect.Slice {
return data, nil
}
raw := data.(string)
if raw == "" {
return []string{}, nil
}
return strings.Split(raw, ","), nil
}
}