-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.go
More file actions
171 lines (149 loc) · 4.68 KB
/
Copy pathdecode.go
File metadata and controls
171 lines (149 loc) · 4.68 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
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
package confx
import (
"encoding/base64"
"encoding/json"
"io"
"reflect"
"strconv"
"strings"
"time"
"github.com/go-viper/mapstructure/v2"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
var DecoderConfigOption = func(tagName string) func(dc *mapstructure.DecoderConfig) {
return func(dc *mapstructure.DecoderConfig) {
dc.DecodeHook = mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToTimeHookFunc(time.RFC3339),
StringToSliceHookFunc(","),
StringToMapHookFunc(",", "="),
)
if tagName != "" {
dc.TagName = tagName
} else {
dc.TagName = DefaultTagName
}
}
}
func Read[T any](typ string, r io.Reader) (T, error) {
return ReadWithTagName[T]("", typ, r)
}
func ReadWithTagName[T any](tagName string, typ string, r io.Reader) (T, error) {
var zero T
viperInstance := viper.New()
viperInstance.SetConfigType(strings.TrimLeft(typ, "."))
if err := viperInstance.ReadConfig(r); err != nil {
return zero, errors.Wrap(err, "failed to read config")
}
var def T
if err := viperInstance.Unmarshal(&def, DecoderConfigOption(tagName)); err != nil {
return zero, errors.Wrap(err, "failed to unmarshal config")
}
return def, nil
}
func StringToSliceHookFunc(separator string) mapstructure.DecodeHookFunc {
return func(from reflect.Type, to reflect.Type, data any) (any, error) {
if from.Kind() == reflect.String && to.Kind() == reflect.Slice {
elemType := to.Elem()
if unwrapType(elemType).Kind() == reflect.Struct {
sliceValue := reflect.New(to).Elem()
err := json.Unmarshal([]byte(data.(string)), sliceValue.Addr().Interface())
if err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal json, data: %s", data)
}
return sliceValue.Interface(), nil
}
str := strings.Trim(data.(string), "[]")
if to == reflect.TypeOf([]byte{}) {
return base64.StdEncoding.DecodeString(str)
}
parts := strings.Split(str, separator)
switch elemType.Kind() {
case reflect.Bool:
return parseSlice(parts, strconv.ParseBool)
case reflect.Float32, reflect.Float64:
return parseSlice(parts, func(s string) (float64, error) {
return strconv.ParseFloat(s, 64)
})
case reflect.Int, reflect.Int32, reflect.Int64:
if elemType == typeDuration {
// nolint:gocritic
return parseSlice(parts, func(s string) (time.Duration, error) {
return time.ParseDuration(s)
})
}
return parseSlice(parts, func(s string) (int64, error) {
return strconv.ParseInt(s, 10, 64)
})
case reflect.String:
return parts, nil
case reflect.Uint, reflect.Uint32, reflect.Uint64:
return parseSlice(parts, func(s string) (uint64, error) {
return strconv.ParseUint(s, 10, 64)
})
default:
return nil, errors.Errorf("unsupported slice element type %q", elemType)
}
}
return data, nil
}
}
func parseSlice[T any](parts []string, parseFunc func(string) (T, error)) ([]T, error) {
if len(parts) == 0 ||
(len(parts) == 1 && strings.TrimSpace(parts[0]) == "") {
return []T{}, nil
}
result := make([]T, len(parts))
for i, part := range parts {
parsed, err := parseFunc(strings.TrimSpace(part))
if err != nil {
return nil, errors.Wrapf(err, "invalid value %q", part)
}
result[i] = parsed
}
return result, nil
}
func StringToMapHookFunc(separator string, pairSeparator string) mapstructure.DecodeHookFunc {
return func(from reflect.Type, to reflect.Type, data any) (any, error) {
if from.Kind() == reflect.String && to.Kind() == reflect.Map {
str := strings.Trim(data.(string), "[]{}")
if str == "" {
return reflect.MakeMap(to).Interface(), nil
}
pairs := strings.Split(str, separator)
keyType := to.Key()
elemType := to.Elem()
if keyType.Kind() != reflect.String {
return nil, errors.Errorf("only string keys are supported for map type, got %q", keyType)
}
result := reflect.MakeMap(to)
for _, pair := range pairs {
kv := strings.SplitN(pair, pairSeparator, 2)
if len(kv) != 2 {
return nil, errors.Errorf("invalid key-value pair %q", pair)
}
key := kv[0]
valueStr := kv[1]
var value any
var err error
switch elemType.Kind() {
case reflect.Int:
value, err = strconv.Atoi(strings.TrimSpace(valueStr))
case reflect.Int64:
value, err = strconv.ParseInt(strings.TrimSpace(valueStr), 10, 64)
case reflect.String:
value = valueStr
default:
return nil, errors.Errorf("unsupported map value type %q", elemType)
}
if err != nil {
return nil, errors.Wrapf(err, "invalid value %q for key %q", valueStr, key)
}
result.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))
}
return result.Interface(), nil
}
return data, nil
}
}