-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
108 lines (86 loc) · 2.14 KB
/
map.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
package populate_struct
import (
"fmt"
"reflect"
"strings"
)
// MapToStruct function to populate struct fields from map values
func MapToStruct(resultPointer any, data map[string]string, escapePath string) error {
var (
esc []string
escLen int
)
if len(escapePath) > 0 {
esc = strings.Split(escapePath, SPLIT_CHAR)
escLen = len(esc)
}
for key, value := range data {
fields := strings.Split(key, SPLIT_CHAR)
// if escapePath && 'key' not have escape path: not process 'key'
if len(escapePath) > 0 && !haveEscapePath(fields, esc) {
continue
}
if err := fromPathAndValue(resultPointer, fields[escLen:], value); err != nil {
return err
}
}
return nil
}
func haveEscapePath(fields, esc []string) bool {
if len(esc) >= len(fields) {
return false
}
for i, e := range esc {
if fields[i] != e {
return false
}
}
return true
}
// Function to set a field value using a path of JSON tags
func fromPathAndValue(obj any, fields []string, value string) error {
// Get the final field to set the value
finalField, err := findField(obj, fields)
if err != nil {
if err == ErrFieldNotFound {
return nil
}
return err
}
// Set the value of the final field
if !finalField.CanSet() {
return fmt.Errorf("cannot set field with tag: %s", fields[len(fields)-1])
}
val, err := convertStringToType(value, finalField.Type())
if err != nil {
return err
}
finalField.Set(val)
return nil
}
func findField(obj any, path []string) (reflect.Value, error) {
val := reflect.ValueOf(obj)
if val.Kind() == reflect.Ptr {
val = val.Elem() // Dereference pointer
}
for _, field := range path {
val = val.FieldByName(field)
if !val.IsValid() {
return val, ErrFieldNotFound
}
if val.Kind() == reflect.Ptr {
val = val.Elem() // Dereference pointer if the field is a pointer
}
}
return val, nil
}
//////////////////////////////////////////////////////////////////////////////////////
func GetFieldValue(obj any, path string) (any, error) {
// Split the path into fields
fields := strings.Split(path, SPLIT_CHAR)
val, err := findField(obj, fields)
if err != nil {
return nil, err
}
return val.Interface(), nil
}