-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflect.go
387 lines (328 loc) · 9.02 KB
/
reflect.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
package probe
import (
"encoding/json"
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
const (
flatkey = "__"
tagMap = "map"
tagValidate = "validate"
labelRequired = "required"
)
// merge string maps
func MergeStringMaps(base map[string]string, over map[string]any) map[string]string {
res := make(map[string]string)
for k, v := range base {
res[k] = v
}
for k, v := range over {
if value, ok := v.(string); ok {
res[k] = value
}
}
return res
}
// MergeMaps merges two maps of type map[string]any.
// If keys conflict, the values from over override those in base.
// Nested maps are merged recursively.
func MergeMaps(base, over map[string]any) map[string]any {
merged := make(map[string]any)
// Copy all entries from base into the result
for key, value := range base {
merged[key] = value
}
// Merge entries from over, overriding base's values if keys conflict
for key, value := range over {
if existing, ok := merged[key]; ok {
// If both values are maps, merge them recursively
if map1Nested, ok1 := existing.(map[string]any); ok1 {
if map2Nested, ok2 := value.(map[string]any); ok2 {
merged[key] = MergeMaps(map1Nested, map2Nested)
continue
}
}
}
// Otherwise, overwrite the value from over
merged[key] = value
}
return merged
}
// converting from a map[string]any to a struct
func MapToStructByTags(params map[string]any, dest any) error {
val := reflect.ValueOf(dest).Elem()
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
// get the map tag
mapTag := fieldType.Tag.Get(tagMap)
if mapTag == "" {
continue
}
// get the validate tag
validateTag := fieldType.Tag.Get(tagValidate)
// when nested struct
if field.Kind() == reflect.Struct {
nestedParams, ok := params[mapTag].(map[string]any)
if !ok && validateTag == labelRequired {
return fmt.Errorf("required field '%s' is missing or not a map[string]any", mapTag)
} else if ok {
// recursively assigning a map
err := MapToStructByTags(nestedParams, field.Addr().Interface())
if err != nil {
return err
}
}
// when the field is a map[string]string
} else if field.Type() == reflect.TypeOf(map[string]string{}) {
v, ok := params[mapTag].(map[string]interface{})
if !ok && validateTag == labelRequired {
return fmt.Errorf("expected map[string]interface{} for field '%s'", mapTag)
} else {
existingMap := field.Interface().(map[string]string)
mergedMap := MergeStringMaps(existingMap, v)
field.Set(reflect.ValueOf(mergedMap))
}
// when the field is []byte
} else if field.Type() == reflect.TypeOf([]byte{}) {
v, ok := params[mapTag].(string)
if !ok && validateTag == labelRequired {
return fmt.Errorf("expected string for field '%s' to convert to []byte", mapTag)
} else {
field.Set(reflect.ValueOf([]byte(v)))
}
} else {
// get the value corresponding to the key from the map
if v, ok := params[mapTag]; ok {
// set a value for a field
if field.CanSet() {
field.Set(reflect.ValueOf(v))
}
// error when required field is missing
} else if validateTag == "required" {
return fmt.Errorf("required field '%s' is missing", mapTag)
}
}
}
return nil
}
// converting from a struct to a map[string]any
func StructToMapByTags(src any) (map[string]any, error) {
result := make(map[string]any)
val := reflect.ValueOf(src)
typ := reflect.TypeOf(src)
// for pointers, access the actual value
if val.Kind() == reflect.Ptr {
val = val.Elem()
typ = typ.Elem()
}
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
// get the map tag
mapTag := fieldType.Tag.Get(tagMap)
if mapTag == "" {
continue
}
// when nested struct
if field.Kind() == reflect.Struct {
nestedMap, err := StructToMapByTags(field.Interface())
if err != nil {
return nil, err
}
result[mapTag] = nestedMap
// when the field is []byte
} else if field.Type() == reflect.TypeOf([]byte{}) {
if b, ok := field.Interface().([]byte); ok {
result[mapTag] = string(b)
}
} else if field.Type() == reflect.TypeOf(map[string]string{}) {
// when the field is a map[string]string
result[mapTag] = field.Interface()
} else {
// when the normal field
result[mapTag] = field.Interface()
}
}
return result, nil
}
func AssignStruct(pa ActionsParams, st any) error {
v := reflect.ValueOf(st).Elem()
t := v.Type()
e := &ValidationError{}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fType := field.Type
mapKey := field.Tag.Get("map")
va := field.Tag.Get("validate")
required := strings.Contains(va, "required")
if mapKey == "" {
continue
}
value, ok := pa[mapKey]
if ok {
switch fType.String() {
case "string":
v.Field(i).SetString(value)
case "int":
intValue, err := strconv.Atoi(value)
if err != nil {
e.AddMessage(fmt.Sprintf("params '%s' can't convert to int: %s", mapKey, err))
} else {
v.Field(i).SetInt(int64(intValue))
}
default:
e.AddMessage(fmt.Sprintf("params '%s' not found", mapKey))
}
}
if required && v.Field(i).String() == "" {
e.AddMessage(fmt.Sprintf("params '%s' is required", mapKey))
}
}
if e.HasError() {
return e
}
return nil
}
func FlattenInterface(i any) map[string]string {
return flattenIf(i, "")
}
func flattenIf(input any, prefix string) map[string]string {
res := make(map[string]string)
if input == nil {
res[prefix] = ""
return res
}
switch reflect.TypeOf(input).Kind() {
case reflect.Map:
// Traverse a map to get keys and values
inputMap := reflect.ValueOf(input)
for _, key := range inputMap.MapKeys() {
// Convert the current key to a string
strKey := fmt.Sprintf("%v", key)
// Underscore prefixes when nested
if prefix != "" {
strKey = prefix + flatkey + strKey
}
// Recursive calls handle nesting
for k, v := range flattenIf(inputMap.MapIndex(key).Interface(), strKey) {
res[k] = v
}
}
case reflect.Slice, reflect.Array:
// Working with slices and arrays (using indexes as keys)
inputSlice := reflect.ValueOf(input)
for i := 0; i < inputSlice.Len(); i++ {
strKey := fmt.Sprintf("%d", i)
if prefix != "" {
strKey = prefix + flatkey + strKey
}
for k, v := range flattenIf(inputSlice.Index(i).Interface(), strKey) {
res[k] = v
}
}
default:
// If it is a basic type, it is stored as is.
res[prefix] = fmt.Sprintf("%v", input)
}
return res
}
// Recursively convert a map[string]string to a map[string]any
func UnflattenInterface(flatMap map[string]string) map[string]any {
result := make(map[string]any)
for key, value := range flatMap {
keys := strings.Split(key, flatkey)
nestMap(result, keys, value)
}
return result
}
// A helper to set values for nested keys
func nestMap(m map[string]any, keys []string, value string) {
if len(keys) == 1 {
// when it is the last key, set the value
if intValue, err := strconv.Atoi(value); err == nil {
m[keys[0]] = intValue
} else {
m[keys[0]] = value
}
} else {
// when there are still keys remaining, create the next level map
if _, exists := m[keys[0]]; !exists {
m[keys[0]] = make(map[string]any)
}
// recursively set the next nested map
nestMap(m[keys[0]].(map[string]any), keys[1:], value)
}
}
func mustMarshalJSON(st string) map[string]any {
var re map[string]any
if err := json.Unmarshal([]byte(st), &re); err != nil {
return map[string]any{
"error_message": fmt.Sprintf("mustMarshalJSON error: %s", err),
}
}
return re
}
func isJSON(st string) bool {
trimmed := strings.TrimSpace(st)
if len(trimmed) < 2 {
return false
}
fChar := rune(trimmed[0])
lChar := rune(trimmed[len(trimmed)-1])
return (fChar == '{' && lChar == '}') || (fChar == '[' && lChar == ']')
}
func TitleCase(st string, char string) string {
parts := strings.Split(st, char)
for i, part := range parts {
if len(part) > 0 {
parts[i] = strings.ToUpper(part[:1]) + part[1:]
}
}
return strings.Join(parts, char)
}
func StrmapToAnymap(strmap map[string]string) map[string]any {
anymap := make(map[string]any)
for k, v := range strmap {
anymap[k] = v
}
return anymap
}
func EnvMap() map[string]string {
env := make(map[string]string)
for _, v := range os.Environ() {
parts := strings.SplitN(v, "=", 2)
if len(parts) == 2 {
env[parts[0]] = parts[1]
}
}
return env
}
// AnyToString attempts to convert any type to a string.
func AnyToString(value any) (string, bool) {
switch v := value.(type) {
case string:
return v, true
case bool:
return strconv.FormatBool(v), true
case int, int8, int16, int32, int64:
return strconv.FormatInt(reflect.ValueOf(v).Int(), 10), true
case uint, uint8, uint16, uint32, uint64:
return strconv.FormatUint(reflect.ValueOf(v).Uint(), 10), true
case float32, float64:
return strconv.FormatFloat(reflect.ValueOf(v).Float(), 'f', -1, 64), true
case []byte:
return string(v), true
case fmt.Stringer:
return v.String(), true
default:
if reflect.ValueOf(value).IsZero() {
return "nil", true
}
return "", false
}
}