-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsac.go
69 lines (59 loc) · 1.2 KB
/
sac.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
package aqua
import (
"github.com/fatih/structs"
"reflect"
)
func init() {
structs.DefaultTagName = "json"
}
type Sac struct {
Data map[string]interface{}
}
func NewSac() *Sac {
return &Sac{Data: make(map[string]interface{})}
}
func (me *Sac) Set(key string, i interface{}) *Sac {
if i == nil {
me.Data[key] = nil
} else {
switch reflect.TypeOf(i).Kind() {
case reflect.Struct:
if s, ok := i.(Sac); ok {
me.Data[key] = s.Data
} else {
me.Data[key] = structs.Map(i)
}
case reflect.Map:
me.Data[key] = i
case reflect.Ptr:
item := reflect.ValueOf(i).Elem().Interface()
me.Set(key, item)
default:
me.Data[key] = i
}
}
return me
}
// Item being merged must be a struct or a map
func (me *Sac) Merge(i interface{}) *Sac {
switch reflect.TypeOf(i).Kind() {
case reflect.Struct:
if s, ok := i.(Sac); ok {
me.Merge(s.Data)
} else {
me.Merge(structs.Map(i))
}
case reflect.Map:
m := i.(map[string]interface{})
for key, val := range m {
if _, exists := me.Data[key]; exists {
panic("Merge field already exists:" + key)
} else {
me.Data[key] = val
}
}
default:
panic("Can't merge something that is not struct or map")
}
return me
}