-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeepmerge.go
75 lines (69 loc) · 1.42 KB
/
deepmerge.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
package deepmerge
import (
"errors"
"reflect"
)
var (
TypeNotMatchErr = errors.New("type not match")
)
func convertSlice(i interface{}) []interface{} {
ret := []interface{}{}
switch i.(type) {
case []interface{}:
return i.([]interface{})
case []string:
for _, v := range i.([]string) {
ret = append(ret, v)
}
return ret
case []int:
for _, v := range i.([]int) {
ret = append(ret, v)
}
return ret
case []float64:
for _, v := range i.([]float64) {
ret = append(ret, v)
}
return ret
case []float32:
for _, v := range i.([]float32) {
ret = append(ret, v)
}
return ret
case []byte:
return append(ret, i)
}
return nil
}
func Merge(src, dst interface{}) (interface{}, error) {
srcType := reflect.TypeOf(src)
dstType := reflect.TypeOf(dst)
if srcType.Kind() != dstType.Kind() {
return nil, TypeNotMatchErr
}
switch srcType.Kind() {
case reflect.Map:
srcMap := src.(map[string]interface{})
for k, dstVal := range dst.(map[string]interface{}) {
srcVal, ok := srcMap[k]
if !ok {
srcMap[k] = dstVal
} else {
mergedVal, err := Merge(srcVal, dstVal)
if err != nil {
return nil, err
}
srcMap[k] = mergedVal
}
}
return src, nil
case reflect.Slice:
//return append(src.([]interface{}), dst.([]interface{})...), nil
srcSlice := convertSlice(src)
dstSlice := convertSlice(dst)
return append(srcSlice, dstSlice...), nil
default:
return src, nil
}
}