github.com/imannamdari/v2ray-core/v5@v5.0.5/infra/conf/merge/map.go (about) 1 // Copyright 2020 Jebbs. All rights reserved. 2 // Use of this source code is governed by MIT 3 // license that can be found in the LICENSE file. 4 5 package merge 6 7 import ( 8 "fmt" 9 "reflect" 10 ) 11 12 // mergeMaps merges source map into target 13 // it supports only map[string]interface{} type for any children of the map tree 14 func mergeMaps(target map[string]interface{}, source map[string]interface{}) (err error) { 15 for key, value := range source { 16 target[key], err = mergeField(target[key], value) 17 if err != nil { 18 return 19 } 20 } 21 return 22 } 23 24 func mergeField(target interface{}, source interface{}) (interface{}, error) { 25 if source == nil { 26 return target, nil 27 } 28 if target == nil { 29 return source, nil 30 } 31 if reflect.TypeOf(source) != reflect.TypeOf(target) { 32 return nil, fmt.Errorf("type mismatch, expect %T, incoming %T", target, source) 33 } 34 if slice, ok := source.([]interface{}); ok { 35 tslice, _ := target.([]interface{}) 36 tslice = append(tslice, slice...) 37 return tslice, nil 38 } else if smap, ok := source.(map[string]interface{}); ok { 39 tmap, _ := target.(map[string]interface{}) 40 err := mergeMaps(tmap, smap) 41 return tmap, err 42 } 43 return source, nil 44 }