viper 如何实现多配置管理

viper 如何实现 下面这种配置的管理:
test.config.yml -> 提交到git
local.config.yml -> 开发者自己的电脑上

在使用 Viper 进行配置管理时,可以通过以下方式实现 test.config.ymllocal.config.yml 的管理:

1. 配置文件结构

  • test.config.yml:提交到 Git 仓库,包含通用的测试环境配置。
  • local.config.yml:不提交到 Git,仅存在于开发者的本地机器上,用于覆盖或补充 test.config.yml 中的配置。

2. 使用 Viper 加载配置

Viper 支持加载多个配置文件,并且后加载的配置会覆盖先加载的配置。因此,可以先加载 test.config.yml,再加载 local.config.yml

package main

import (
    "fmt"
    "github.com/spf13/viper"
)

func main() {
    // 设置配置文件名(不带扩展名)
    viper.SetConfigName("test.config")
    viper.SetConfigType("yml")
    viper.AddConfigPath(".") // 配置文件路径

    // 加载 test.config.yml
    if err := viper.ReadInConfig(); err != nil {
        fmt.Printf("Error reading test.config.yml: %v\n", err)
        return
    }

    // 加载 local.config.yml(如果存在)
    viper.SetConfigName("local.config")
    if err := viper.MergeInConfig(); err != nil {
        fmt.Printf("No local.config.yml found, using only test.config.yml\n")
    }

    // 读取配置
    fmt.Println("Config value:", viper.GetString("some.key"))
}

3. 配置文件的优先级

  • test.config.yml 是基础配置,提交到 Git 仓库。
  • local.config.yml 是本地配置,用于覆盖 test.config.yml 中的某些配置项。

4. 忽略 local.config.yml

.gitignore 文件中添加 local.config.yml,确保它不会被提交到 Git 仓库。

# .gitignore
local.config.yml

5. 示例配置文件

test.config.yml

database:
  host: "localhost"
  port: 3306
  username: "testuser"
  password: "testpass"

local.config.yml

database:
  host: "127.0.0.1"
  username: "devuser"

6. 运行结果

  • 如果 local.config.yml 存在,database.hostdatabase.username 会被覆盖。
  • 如果 local.config.yml 不存在,则使用 test.config.yml 中的配置。

7. 总结

通过 Viper 的 MergeInConfig 方法,可以轻松实现配置文件的覆盖和优先级管理。test.config.yml 作为基础配置提交到 Git,而 local.config.yml 则用于开发者本地的个性化配置。