@@ -89,15 +89,59 @@ import (
89
89
// Field map[string]string `properties:"myName"`
90
90
func (p * Properties ) Decode (x interface {}) error {
91
91
t , v := reflect .TypeOf (x ), reflect .ValueOf (x )
92
- if t .Kind () != reflect .Ptr || v .Elem ().Type ().Kind () != reflect .Struct {
93
- return fmt .Errorf ("not a pointer to struct: %s" , t )
92
+
93
+ if isPtr (t ) {
94
+ elemT := v .Elem ().Type ()
95
+ switch {
96
+ case isMap (elemT ):
97
+ m , ok := x .(* map [string ]interface {})
98
+ if ! ok {
99
+ return fmt .Errorf ("map type not map[string]interface {}" , elemT )
100
+ }
101
+ if err := p .DecodeToStringMap (* m ); err != nil {
102
+ return err
103
+ }
104
+ return nil
105
+
106
+ case isStruct (elemT ):
107
+ if err := dec (p , "" , nil , nil , v ); err != nil {
108
+ return err
109
+ }
110
+ return nil
111
+ }
94
112
}
95
- if err := dec (p , "" , nil , nil , v ); err != nil {
96
- return err
113
+
114
+ return fmt .Errorf ("not a pointer to map or struct: %s" , t )
115
+ }
116
+
117
+ func (p * Properties ) DecodeToStringMap (m map [string ]interface {}) error {
118
+ for _ , key := range p .Keys () {
119
+ value , _ := p .Get (key )
120
+ setNestedKey (m , key , value )
97
121
}
122
+
98
123
return nil
99
124
}
100
125
126
+ func setNestedKey (m map [string ]interface {}, key string , value interface {}) {
127
+ if strings .Contains (key , "." ) {
128
+ kk := strings .SplitN (key , "." , 2 )
129
+ prefix , rest := kk [0 ], kk [1 ]
130
+ if _ , ok := m [prefix ]; ! ok {
131
+ m [prefix ] = make (map [string ]interface {})
132
+ }
133
+ setNestedKey (m [prefix ].(map [string ]interface {}), rest , value )
134
+ } else {
135
+ if reflect .TypeOf (value ).Kind () == reflect .String {
136
+ val := value .(string )
137
+ if strings .Contains (val , ";" ) {
138
+ value = split (val , ";" )
139
+ }
140
+ }
141
+ m [key ] = value
142
+ }
143
+ }
144
+
101
145
func dec (p * Properties , key string , def * string , opts map [string ]string , v reflect.Value ) error {
102
146
t := v .Type ()
103
147
0 commit comments