前言

最近在用 Golang 做前端配置中心服务,想实现配置文件层级加载合并的功能,比如我们有业务域名 ram.console.liusuyun.com 我们希望它可以加载:

  • ram.console.liusuyun.com
  • console.liusuyun.com
  • liusuyun.com

三个配置文件,合并后发送给前端,于是便有了如下功能的开发。


实现

package utils

import (
    "reflect"
)

func MergeMany(sources ...map[string]interface{}) map[string]interface{} {
    base := sources[0]
    if len(sources) > 1 {
        for index, source := range sources {
            if index != 0 {
                MergeBoth(source, base)
            }
        }
    }
    return base
}

func MergeBoth(from map[string]interface{}, to map[string]interface{}) {
    for key, value := range from {
        switch reflect.TypeOf(value).Kind() {
        case reflect.Map:
            if valueGq, ok := to[key]; ok {
                MergeBoth(value.(map[string]interface{}), valueGq.(map[string]interface{}))
            } else {
                to[key] = value
            }
        case reflect.Slice, reflect.Array:
            if valueGq, ok := to[key]; ok {
                valueGyq := make([]interface{}, 0)
                //
                origin := reflect.ValueOf(value)
                for i := 0; i < origin.Len(); i++ {
                    valueGyq = append(valueGyq, origin.Index(i).Interface())
                }
                origin = reflect.ValueOf(valueGq)
                for i := 0; i < origin.Len(); i++ {
                    valueGyq = append(valueGyq, origin.Index(i).Interface())
                }
                //
                to[key] = valueGyq
            } else {
                to[key] = value
            }
        default:
            to[key] = value
        }
    }

}

package utils

import (
    "testing"
)

func TestMergeMany(t *testing.T) {
    x := map[string]interface{}{
        "l": "0",
        "x": "1",
        "y": [...]int{2, 3},
        "z": map[interface{}]interface{}{
            "x": "6",
        },
    }
    y := map[string]interface{}{
        "l": "-1",
        "y": [...]int{4, 5},
        "z": map[interface{}]interface{}{
            "y": "7",
        },
    }

    z := MergeMany(x, y)
    println(z)
}


完结撒花~

最后修改:2022 年 07 月 13 日
如果觉得我的文章对你有用,请随意赞赏