-
Notifications
You must be signed in to change notification settings - Fork 9
/
m.go
386 lines (339 loc) · 8.16 KB
/
m.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
package toolkit
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"time"
)
type M map[string]interface{}
type Ms []M
var ErrorPathNotFound = errors.New("Path requested is not available")
func (m M) Set(k string, v interface{}) M {
m[k] = v
return m
}
func (m M) Sets(vs ...interface{}) M {
k := ""
for i, v := range vs {
if i%2 == 0 {
k, _ = v.(string)
} else {
if k != "" {
m.Set(k, v)
k = ""
}
}
}
return m
}
func (m M) PathSet(k string, v interface{}, pathDelim string) M {
doms := strings.Split(k, pathDelim)
//Logger().Debugf("key:%s doms:%s", k, JsonString(doms))
if len(doms) == 1 {
//Logger().Debugf("Set %s to %v", k, v)
m.Set(doms[0], v)
} else if len(doms) > 1 {
map0 := M{}
dom0 := m.Get(doms[0])
if reflect.Indirect(reflect.ValueOf(dom0)).Kind() == reflect.Map {
map0, _ = ToM(dom0)
}
map0.PathSet(strings.Join(doms[1:], pathDelim), v, pathDelim)
//Logger().Debugf("Iterate child %s to v", k, v)
m.Set(doms[0], map0)
}
//Logger().Debugf("M: %s", JsonString(m))
return m
}
func (m M) Get(k string, d ...interface{}) interface{} {
if get, b := m[k]; b {
if IsNilOrEmpty(get) && len(d) > 0 {
get = d[0]
}
return get
} else {
if len(d) > 0 {
return d[0]
} else {
return nil
}
}
}
func (m M) GetRef(k string, d, out interface{}) {
/*
defer func() {
if r := recover(); r != nil {
}
}()
*/
valget := reflect.Indirect(reflect.ValueOf(m.Get(k, d)))
valout := reflect.ValueOf(out)
valout.Elem().Set(valget)
}
const (
CaseAsIs string = ""
CaseUpper = "upper"
CaseLower = "lower"
)
var (
DefaultCase = CaseAsIs
)
func ToMCase(data interface{}, casePattern string) (M, error) {
return tom(data, casePattern)
}
func ToM(data interface{}) (M, error) {
return tom(data, DefaultCase)
}
func ToMTag(data interface{}, tagName string) (M, error) {
return tomTagName(data, DefaultCase, tagName)
}
var _tagName string
func TagName() string {
if _tagName == "" {
_tagName = "json"
}
return _tagName
}
func SetTagName(name string) {
_tagName = name
}
func tom(data interface{}, namePattern string) (M, error) {
return tomTagName(data, namePattern, TagName())
}
func tomTagName(data interface{}, namePattern string, tagName string) (M, error) {
rv := reflect.Indirect(reflect.ValueOf(data))
// Create emapty map as a result
res := M{}
// Because of the difference behaviour of Struct type and Map type, we need to check the data element type
if rv.Kind() == reflect.Struct {
// Iterate through all the available field
for i := 0; i < rv.NumField(); i++ {
// Get the field type
f := rv.Type().Field(i)
fieldName := f.Name
fieldTagNames := strings.Split(f.Tag.Get(tagName), ",")
/*
if len(fieldTagNames) > 1 && fieldTagNames[1] == "omitempty" && f {
continue
}
*/
fieldTagName := fieldTagNames[0]
if fieldTagName != "" {
fieldName = fieldTagName
}
if fieldName == "-" {
continue
}
switch namePattern {
case CaseLower:
fieldName = strings.ToLower(fieldName)
case CaseUpper:
fieldName = strings.ToUpper(fieldName)
}
// If the type is struct but not time.Time or is a map
kind := f.Type.Kind()
if kind == reflect.Ptr {
kind = f.Type.Elem().Kind()
} else if (kind == reflect.Struct && f.Type != reflect.TypeOf(time.Time{})) || kind == reflect.Map {
// Then we need to call this function again to fetch the sub value
subRes, err := tomTagName(rv.Field(i).Interface(), namePattern, tagName)
if err != nil {
return nil, err
}
res[fieldName] = subRes
// Skip the rest
continue
} else if kind == reflect.Slice {
slice := rv.Field(i)
count := slice.Len()
elemType := slice.Type().Elem().Kind()
switch elemType {
case reflect.Map, reflect.Struct, reflect.Ptr, reflect.Slice:
ms := make([]M, count)
for si := 0; si < count; si++ {
data := slice.Index(si)
datam, err := tomTagName(data.Interface(), namePattern, tagName)
if err != nil {
return nil, err
}
ms[si] = datam
}
res[fieldName] = ms
default:
res[fieldName] = slice.Interface()
}
continue
}
// If the type is time.Time or is not struct and map then put it in the result directly
func() {
defer func() {
if rec := recover(); rec != nil {
//-- currently do nothing
}
}()
res[fieldName] = rv.Field(i).Interface()
}()
}
// Return the result
return res, nil
} else if rv.Kind() == reflect.Map {
// If the data element is kind of map
// Iterate through all avilable keys
for _, key := range rv.MapKeys() {
// Get the map value type of the specified key
if elem := reflect.Indirect(rv.MapIndex(key)); elem.IsValid() {
t := elem.Type()
// If the type is struct but not time.Time or is a map
if (t.Kind() == reflect.Struct && t != reflect.TypeOf(time.Time{})) || t.Kind() == reflect.Map {
// Then we need to call this function again to fetch the sub value
subRes, err := tom(rv.MapIndex(key).Interface(), namePattern)
if err != nil {
return nil, err
}
res[key.String()] = subRes
// Skip the rest
continue
}
}
// If the type is time.Time or is not struct and map then put it in the result directly
res[key.String()] = rv.MapIndex(key).Interface()
}
// Return the result
return res, nil
}
// If the data element is not map or struct then return error
return nil, Errorf("Expecting struct or map object but got %s", rv.Kind())
}
func (m M) ToBytes(encodertype string, others ...interface{}) []byte {
encodertype = strings.ToLower(encodertype)
if encodertype == "" {
encodertype = "json"
}
/*
if encodertype == "json" {
bs, e := json.Marshal(m)
if e != nil {
return []byte{}
}
return bs
}
*/
return ToBytes(m, encodertype)
//return []byte{}
}
func (m *M) Cast(k string, d interface{}) error {
var e error
if m.Has(k) == false {
return fmt.Errorf("No data for key %s", k)
}
b, e := json.Marshal(m.Get(k, nil))
if e != nil {
return e
}
e = json.Unmarshal(b, d)
return e
}
func (m M) GetBytes(k string) []byte {
bs, err := base64.StdEncoding.DecodeString(m.GetString(k))
if err != nil {
return []byte{}
}
return bs
}
func (m M) GetFloat64(k string) float64 {
i := m.Get(k, 0)
return ToFloat64(i, 6, RoundingAuto)
}
func (m M) GetString(k string) string {
s := m.Get(k, "")
return ToString(s)
}
func (m M) GetInt(k string) int {
i := m.Get(k, 0)
return ToInt(i, RoundingAuto)
}
func (m *M) Unset(k string) {
delete(*m, k)
}
func (m M) GetFloat32(k string) float32 {
i := m.Get(k, 0)
return ToFloat32(i, 6, RoundingAuto)
}
func (m M) GetBool(k string) bool {
b := strings.ToLower(m.GetString(k))
return b == "1" || b == "true" || b == "y" || b == "t" || b == "yes"
}
func (m M) Has(k string) bool {
_, has := m[k]
return has
}
func (m M) PathGet(path string) (interface{}, error) {
pathlist := strings.Split(path, ".")
var curobj interface{} = m
for _, nextpath := range pathlist {
switch curobj.(type) {
case M:
curM := curobj.(M)
var found bool
curobj, found = curM[nextpath]
if !found {
return nil, ErrorPathNotFound
}
case map[string]interface{}:
curM := curobj.(map[string]interface{})
var found bool
curobj, found = curM[nextpath]
if !found {
return nil, ErrorPathNotFound
}
default:
return nil, ErrorPathNotFound
}
}
return curobj, nil
}
func (m M) Keys() []string {
var ret []string
for k, _ := range m {
ret = append(ret, k)
}
return ret
}
func (m M) Values() []interface{} {
var ret []interface{}
for _, v := range m {
ret = append(ret, v)
}
return ret
}
func CopyM(from, to *M,
copyFieldIfNotExist bool,
exceptFields []string) {
//Printf("Copy from: %s to %s\n", JsonString(from), JsonString(to))
var exceptFieldsIface []interface{}
Serde(exceptFields, &exceptFieldsIface, "")
fromm := *from
tom := *to
for f, fv := range fromm {
if !HasMember(exceptFieldsIface, f) {
if tom.Has(f) {
tom.Set(f, fv)
} else if copyFieldIfNotExist {
tom.Set(f, fv)
}
}
}
*to = tom
}
func (m M) Merge(from M, overwrite bool) {
for k, v := range from {
_, ok := m[k]
if ok && !overwrite {
continue
}
m[k] = v
}
}