1 介绍
1.1 简介
01.配置管理库
Go配置解决方案、多源配置、类型安全、功能完整
02.核心特性
多格式支持、环境变量、远程配置、热更新
03.设计理念
12-Factor App、配置分离、灵活易用、生产就绪
04.应用场景
Web应用、微服务、CLI工具、配置中心
1.2 核心特性
01.多源配置
a.配置文件
a.基础使用
import "github.com/spf13/viper"
// 读取配置文件
viper.SetConfigName("config") // 配置文件名(不含扩展名)
viper.SetConfigType("yaml") // 配置文件类型
viper.AddConfigPath(".") // 配置文件路径
viper.AddConfigPath("./config") // 可以添加多个路径
if err := viper.ReadInConfig(); err != nil {
log.Fatal("读取配置失败:", err)
}
// 获取配置
dbHost := viper.GetString("database.host")
dbPort := viper.GetInt("database.port")
debug := viper.GetBool("debug")
fmt.Printf("Database: %s:%d\n", dbHost, dbPort)
b.配置文件示例
// config.yaml
server:
host: 0.0.0.0
port: 8080
mode: release
database:
host: localhost
port: 5432
name: myapp
user: postgres
password: secret
max_connections: 100
redis:
host: localhost
port: 6379
db: 0
password: ""
log:
level: info
format: json
output: stdout
// 读取配置
serverPort := viper.GetInt("server.port")
dbConfig := viper.GetStringMapString("database")
logLevel := viper.GetString("log.level")
b.环境变量
a.环境变量读取
// 自动绑定环境变量
viper.AutomaticEnv()
// 设置环境变量前缀
viper.SetEnvPrefix("MYAPP") // 环境变量前缀
// 绑定环境变量
viper.BindEnv("database.host", "DB_HOST")
viper.BindEnv("database.port", "DB_PORT")
// 读取环境变量
dbHost := viper.GetString("database.host") // 从 MYAPP_DATABASE_HOST 读取
// 使用示例:
// export MYAPP_DATABASE_HOST=localhost
// export MYAPP_DATABASE_PORT=5432
// 替换环境变量中的字符
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// database.host -> DATABASE_HOST
c.命令行参数
a.pflag集成
import (
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// 定义命令行参数
pflag.String("config", "", "配置文件路径")
pflag.Int("port", 8080, "服务端口")
pflag.Bool("debug", false, "调试模式")
pflag.Parse()
// 绑定到viper
viper.BindPFlags(pflag.CommandLine)
// 读取参数
port := viper.GetInt("port")
debug := viper.GetBool("debug")
// 使用:
// ./app --port=3000 --debug=true
d.默认值
a.设置默认值
// 设置默认值
viper.SetDefault("server.port", 8080)
viper.SetDefault("server.host", "0.0.0.0")
viper.SetDefault("database.max_connections", 100)
viper.SetDefault("log.level", "info")
// 批量设置默认值
defaults := map[string]interface{}{
"server.port": 8080,
"server.host": "0.0.0.0",
"database.pool": 10,
"cache.enabled": true,
}
for key, value := range defaults {
viper.SetDefault(key, value)
}
// 优先级:
// 1. 显式调用Set
// 2. 命令行参数
// 3. 环境变量
// 4. 配置文件
// 5. 默认值
02.格式支持
a.多格式配置
a.YAML格式
// config.yaml
server:
port: 8080
host: localhost
// 读取
viper.SetConfigType("yaml")
viper.ReadInConfig()
b.JSON格式
// config.json
{
"server": {
"port": 8080,
"host": "localhost"
},
"database": {
"host": "localhost",
"port": 5432
}
}
// 读取
viper.SetConfigType("json")
viper.ReadInConfig()
c.TOML格式
# config.toml
[server]
port = 8080
host = "localhost"
[database]
host = "localhost"
port = 5432
# 读取
viper.SetConfigType("toml")
viper.ReadInConfig()
03.配置监听
a.热更新
a.文件监听
// 监听配置文件变化
viper.WatchConfig()
// 配置变更回调
viper.OnConfigChange(func(e fsnotify.Event) {
log.Printf("配置文件已更改: %s", e.Name)
// 重新读取配置
newPort := viper.GetInt("server.port")
log.Printf("新端口: %d", newPort)
// 触发应用重新加载配置
reloadConfig()
})
// 完整示例
func main() {
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.ReadInConfig()
// 启用热更新
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Println("配置已更新")
// 应用新配置
})
// 启动应用
startServer()
}
04.类型安全
a.类型方法
a.Get系列方法
// 基础类型
str := viper.GetString("key")
num := viper.GetInt("key")
float := viper.GetFloat64("key")
bool := viper.GetBool("key")
// 时间类型
duration := viper.GetDuration("timeout") // "300ms", "1.5h"
time := viper.GetTime("created_at")
// 复杂类型
stringSlice := viper.GetStringSlice("tags")
stringMap := viper.GetStringMap("database")
stringMapString := viper.GetStringMapString("labels")
// 完整示例
type Config struct {
Server struct {
Port int `mapstructure:"port"`
Host string `mapstructure:"host"`
} `mapstructure:"server"`
Database struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
} `mapstructure:"database"`
}
var config Config
if err := viper.Unmarshal(&config); err != nil {
log.Fatal(err)
}
fmt.Printf("Server: %s:%d\n", config.Server.Host, config.Server.Port)
1.3 配置来源
01.配置文件
a.本地文件
viper.SetConfigFile("./config.yaml") // 指定完整路径
viper.SetConfigName("config") // 文件名(不含扩展名)
viper.AddConfigPath(".") // 搜索路径
viper.AddConfigPath("/etc/myapp/")
02.环境变量
a.ENV读取
viper.AutomaticEnv() // 自动读取环境变量
viper.SetEnvPrefix("MYAPP") // 前缀
viper.BindEnv("database.host") // 绑定
03.命令行参数
a.pflag集成
pflag.String("config", "", "配置文件路径")
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
04.远程配置
a.配置中心
viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/myapp")
viper.ReadRemoteConfig()
05.默认值
a.兜底配置
viper.SetDefault("server.port", 8080)
viper.SetDefault("database.max_connections", 100)
1.4 使用场景
01.Web应用
a.服务配置
type Config struct {
Server ServerConfig
Database DatabaseConfig
Redis RedisConfig
}
viper.Unmarshal(&config)
02.微服务
a.配置中心
viper.AddRemoteProvider("consul", "localhost:8500", "/config/service")
viper.WatchRemoteConfig()
03.CLI工具
a.命令行配置
viper.BindPFlags(cmd.Flags())
configFile := viper.GetString("config")
04.多环境部署
a.环境切换
env := os.Getenv("APP_ENV")
viper.SetConfigName(fmt.Sprintf("config.%s", env))
1.5 快速开始
01.安装
a.安装命令
go get github.com/spf13/viper
02.基础使用
a.完整示例
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.ReadInConfig()
port := viper.GetInt("server.port")
fmt.Println("Server port:", port)
03.读取配置
a.类型方法
viper.GetString("database.host")
viper.GetInt("server.port")
viper.GetBool("debug")
viper.GetFloat64("timeout")
viper.GetStringSlice("allowed_hosts")
04.设置配置
a.运行时设置
viper.Set("server.port", 9090)
viper.WriteConfig() // 持久化到文件
2 配置读取
2.1 汇总:5个
01.文件配置
配置文件、路径、格式、读取
02.环境变量
ENV读取、前缀、自动绑定、映射
03.命令行参数
pflag、参数绑定、覆盖、优先级
04.远程配置
etcd、Consul、动态读取、监听
05.默认值
SetDefault、兜底、初始化、类型
2.2 文件配置
01.配置文件
a.配置文件读取
viper.SetConfigFile("./config.yaml")
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.AddConfigPath("/etc/myapp/")
02.读取配置
a.错误处理
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Println("配置文件未找到")
} else {
log.Fatal("读取配置失败:", err)
}
}
03.多配置文件
a.配置合并
viper.SetConfigName("config.base")
viper.ReadInConfig()
viper.SetConfigName("config.prod")
viper.MergeInConfig() // 合并配置
04.配置格式
a.格式指定
viper.SetConfigType("yaml") // yaml, json, toml, ini
2.3 环境变量
01.自动绑定
a.自动读取
viper.AutomaticEnv()
dbHost := viper.GetString("database.host") // 从 DATABASE_HOST 读取
02.前缀设置
a.命名空间
viper.SetEnvPrefix("MYAPP")
// database.host -> MYAPP_DATABASE_HOST
03.环境变量映射
a.键映射
viper.BindEnv("database.host", "DB_HOST")
viper.BindEnv("database.port", "DB_PORT")
04.替换规则
a.字符替换
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
2.4 命令行参数
01.pflag集成
a.批量绑定
pflag.String("host", "localhost", "服务器地址")
pflag.Int("port", 8080, "服务器端口")
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
02.单个绑定
a.指定绑定
pflag.String("config", "", "配置文件路径")
viper.BindPFlag("config_file", pflag.Lookup("config"))
03.优先级
a.优先级顺序
// 1. 命令行参数(最高)
// 2. 环境变量
// 3. 配置文件
// 4. 默认值(最低)
04.Cobra集成
a.Cobra示例
cmd.Flags().StringP("config", "c", "", "配置文件")
viper.BindPFlag("config", cmd.Flags().Lookup("config"))
2.5 远程配置
01.etcd支持
a.etcd配置
import _ "github.com/spf13/viper/remote"
viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/myapp")
viper.SetConfigType("json")
err := viper.ReadRemoteConfig()
02.Consul支持
a.Consul配置
viper.AddRemoteProvider("consul", "localhost:8500", "/config/myapp")
viper.SetConfigType("json")
viper.ReadRemoteConfig()
03.配置监听
a.热更新
go func() {
for {
time.Sleep(time.Second * 5)
err := viper.WatchRemoteConfig()
if err != nil {
log.Println("配置更新失败:", err)
}
}
}()
04.安全连接
a.TLS配置
viper.AddSecureRemoteProvider("etcd", "127.0.0.1:4001", "/config/myapp", "/path/to/cert.pem")
2.6 默认值
01.设置默认值
a.基础设置
viper.SetDefault("server.port", 8080)
viper.SetDefault("database.max_connections", 100)
viper.SetDefault("log.level", "info")
02.批量设置
a.批量初始化
defaults := map[string]interface{}{
"server.port": 8080,
"server.host": "0.0.0.0",
"debug": false,
}
for key, value := range defaults {
viper.SetDefault(key, value)
}
03.使用场景
a.兜底配置
// 提供默认值,配置文件中可以不设置
viper.SetDefault("timeout", 30)
timeout := viper.GetInt("timeout") // 如果未配置,返回30
04.优先级
a.最低优先级
// 优先级:Set > 命令行 > 环境变量 > 配置文件 > 默认值
viper.SetDefault("port", 8080) // 最低
// 配置文件中的值会覆盖默认值
3 配置格式
3.1 JSON格式
01.JSON配置
a.JSON示例
// config.json
{
"server": {
"host": "0.0.0.0",
"port": 8080
},
"database": {
"host": "localhost",
"port": 5432
}
}
02.读取JSON
a.读取方式
viper.SetConfigType("json")
viper.SetConfigFile("config.json")
viper.ReadInConfig()
03.JSON特点
a.优势
// 1. 广泛支持
// 2. 工具丰富
// 3. API友好
// 4. 跨语言兼容
04.使用场景
a.适用场景
// API配置、数据交换、跨语言项目
3.2 YAML格式
01.YAML配置
a.YAML示例
# config.yaml
server:
host: 0.0.0.0
port: 8080
mode: release
database:
host: localhost
port: 5432
name: myapp
02.读取YAML
a.读取方式
viper.SetConfigType("yaml")
viper.SetConfigFile("config.yaml")
viper.ReadInConfig()
03.YAML特点
a.优势
// 1. 可读性强
// 2. 支持注释
// 3. 层次清晰
// 4. 复杂结构支持
04.使用场景
a.适用场景
// 应用配置、K8s、Docker Compose、CI/CD
3.3 TOML格式
01.TOML配置
a.TOML示例
# config.toml
[server]
host = "0.0.0.0"
port = 8080
[database]
host = "localhost"
port = 5432
name = "myapp"
02.读取TOML
a.读取方式
viper.SetConfigType("toml")
viper.SetConfigFile("config.toml")
viper.ReadInConfig()
03.TOML特点
a.优势
// 1. 语义清晰
// 2. 类型明确
// 3. 易于解析
04.使用场景
a.适用场景
// Rust项目、Cargo配置、项目配置
3.4 INI格式
01.INI配置
a.INI示例
; config.ini
[server]
host = 0.0.0.0
port = 8080
[database]
host = localhost
port = 5432
02.读取INI
a.读取方式
viper.SetConfigType("ini")
viper.SetConfigFile("config.ini")
viper.ReadInConfig()
03.INI特点
a.优势
// 1. 简单易用
// 2. 广泛支持
// 3. 历史悠久
04.使用场景
a.适用场景
// Windows应用、传统系统、简单配置
3.5 自定义格式
01.自定义解析
a.自定义解析器
// 实现自定义配置解析器
viper.SetConfigType("custom")
02.二进制格式
a.二进制配置
// 使用 protobuf 或 msgpack
03.加密配置
a.配置加密
// 加密敏感配置
encryptedConfig := encrypt(config)
04.使用场景
a.适用场景
// 特殊需求、安全要求、性能优化
4 配置操作
4.1 读取配置
01.Get方法
a.基础读取
value := viper.Get("server.port")
port, ok := value.(int)
02.类型方法
a.类型安全
host := viper.GetString("server.host")
port := viper.GetInt("server.port")
debug := viper.GetBool("debug")
timeout := viper.GetFloat64("timeout")
hosts := viper.GetStringSlice("allowed_hosts")
03.嵌套读取
a.层次访问
dbHost := viper.GetString("database.host")
dbConfig := viper.GetStringMapString("database")
04.默认值
a.提供默认
port := viper.GetInt("server.port")
if port == 0 {
port = 8080 // 默认值
}
4.2 设置配置
01.Set方法
a.运行时设置
viper.Set("server.port", 9090)
viper.Set("debug", true)
02.批量设置
a.批量更新
config := map[string]interface{}{
"server.port": 9090,
"debug": true,
}
viper.MergeConfigMap(config)
03.持久化
a.写入文件
viper.WriteConfig() // 写入当前配置文件
viper.SafeWriteConfig() // 安全写入(不覆盖)
viper.WriteConfigAs("new_config.yaml") // 写入新文件
04.优先级
a.最高优先级
// Set 设置的值优先级最高,覆盖所有其他源
4.3 配置监听
01.文件监听
a.自动重载
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("配置文件变化:", e.Name)
})
02.变更回调
a.回调函数
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("配置更新")
// 重新加载配置
newPort := viper.GetInt("server.port")
fmt.Println("新端口:", newPort)
})
03.远程监听
a.实时更新
go func() {
for {
time.Sleep(time.Second * 5)
viper.WatchRemoteConfig()
}
}()
04.注意事项
a.并发安全
// 使用互斥锁保证并发安全
var mu sync.RWMutex
viper.OnConfigChange(func(e fsnotify.Event) {
mu.Lock()
defer mu.Unlock()
// 更新配置
})
4.4 配置合并
01.MergeInConfig
a.合并文件
viper.SetConfigName("config.base")
viper.ReadInConfig()
viper.SetConfigName("config.prod")
viper.MergeInConfig() // 合并配置
02.MergeConfigMap
a.合并Map
override := map[string]interface{}{
"server.port": 9090,
"debug": false,
}
viper.MergeConfigMap(override)
03.合并策略
a.深度合并
// 深度合并,不覆盖整个对象
04.使用场景
a.多环境配置
// base + env 配置模式
4.5 配置别名
01.RegisterAlias
a.设置别名
viper.RegisterAlias("oldkey", "newkey")
value := viper.Get("oldkey") // 访问 oldkey 实际读取 newkey
02.使用场景
a.配置迁移
// 向后兼容,支持旧配置名
03.别名查找
a.自动解析
// 透明访问,无需修改代码
04.最佳实践
a.文档说明
// 文档中说明别名,逐步废弃旧名称
4.6 类型转换
01.自动转换
a.类型转换
// 字符串 -> 数字
port := viper.GetInt("server.port") // "8080" -> 8080
// 字符串 -> 布尔
debug := viper.GetBool("debug") // "true" -> true
02.自定义转换
a.结构体映射
type DatabaseConfig struct {
Host string
Port int
}
var dbConfig DatabaseConfig
viper.UnmarshalKey("database", &dbConfig)
03.转换错误
a.错误处理
port := viper.GetInt("server.port")
if port == 0 {
log.Fatal("端口配置错误")
}
04.类型安全
a.使用类型方法
// 优先使用 GetString, GetInt 等类型方法
host := viper.GetString("server.host")
5 高级功能
5.1 配置结构体
01.Unmarshal
a.完整映射
type Config struct {
Server ServerConfig
Database DatabaseConfig
}
var config Config
viper.Unmarshal(&config)
02.UnmarshalKey
a.部分映射
type DatabaseConfig struct {
Host string
Port int
}
var dbConfig DatabaseConfig
viper.UnmarshalKey("database", &dbConfig)
03.结构体标签
a.mapstructure标签
type ServerConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
}
04.嵌套结构
a.复杂结构
type Config struct {
Server struct {
Host string
Port int
}
Database struct {
Host string
Port int
}
}
5.2 配置验证
01.必填验证
a.检查必需配置
if !viper.IsSet("database.host") {
log.Fatal("数据库地址未配置")
}
02.格式验证
a.范围检查
port := viper.GetInt("server.port")
if port < 1024 || port > 65535 {
log.Fatal("端口范围错误")
}
03.依赖验证
a.条件检查
if viper.GetBool("https.enabled") {
if !viper.IsSet("https.cert") {
log.Fatal("HTTPS已启用,但未配置证书")
}
}
04.验证时机
a.启动验证
func ValidateConfig() error {
// 在应用启动时验证配置
return nil
}
5.3 配置加密
01.敏感信息
a.敏感配置
// 不要将密码、密钥写入配置文件
// 使用环境变量
dbPassword := viper.GetString("database.password") // 从 ENV 读取
02.加密存储
a.配置加密
// 使用加密工具加密配置文件
// 运行时解密
03.环境变量
a.使用ENV
// export DB_PASSWORD=secret
viper.BindEnv("database.password", "DB_PASSWORD")
04.密钥管理
a.Vault集成
// 使用 HashiCorp Vault 管理密钥
5.4 热更新
01.文件监听
a.自动重载
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("配置热更新")
// 无需重启应用
})
02.远程监听
a.实时推送
go func() {
for {
time.Sleep(5 * time.Second)
viper.WatchRemoteConfig()
}
}()
03.更新策略
a.全量更新
// 重新加载所有配置
04.注意事项
a.并发安全
// 使用锁保证线程安全
5.5 多环境配置
01.环境隔离
a.环境分离
env := os.Getenv("APP_ENV")
viper.SetConfigName(fmt.Sprintf("config.%s", env))
// config.dev.yaml, config.prod.yaml
02.配置继承
a.base + env
viper.SetConfigName("config.base")
viper.ReadInConfig()
viper.SetConfigName("config." + env)
viper.MergeInConfig()
03.环境切换
a.ENV变量
// export APP_ENV=prod
// go run main.go
04.最佳实践
a.配置模板
// config.base.yaml - 通用配置
// config.dev.yaml - 开发环境
// config.prod.yaml - 生产环境
6 集成应用
6.1 与Cobra集成
01.Cobra简介
a.CLI框架
import "github.com/spf13/cobra"
02.配置绑定
a.自动绑定
var rootCmd = &cobra.Command{Use: "app"}
rootCmd.PersistentFlags().String("config", "", "config file")
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
03.配置文件
a.初始化
func initConfig() {
if cfgFile := viper.GetString("config"); cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
viper.SetConfigName("config")
viper.AddConfigPath(".")
}
viper.ReadInConfig()
}
04.使用示例
a.完整示例
cobra.OnInitialize(initConfig)
rootCmd.Execute()
6.2 与pflag集成
01.pflag简介
a.POSIX风格
import "github.com/spf13/pflag"
02.参数绑定
a.绑定示例
pflag.String("host", "localhost", "server host")
pflag.Int("port", 8080, "server port")
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
03.优先级
a.命令行最高
// 命令行参数覆盖配置文件
04.使用场景
a.CLI工具
// ./app --port 9090
6.3 配置中心
01.etcd集成
a.etcd配置
viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/app")
viper.SetConfigType("json")
viper.ReadRemoteConfig()
02.Consul集成
a.Consul配置
viper.AddRemoteProvider("consul", "localhost:8500", "/config/app")
viper.ReadRemoteConfig()
03.Apollo/Nacos
a.配置中心
// 使用第三方库集成
04.最佳实践
a.配置分层
// 全局配置 / 应用配置 / 环境配置
6.4 微服务配置
01.服务配置
a.服务发现
viper.AddRemoteProvider("consul", "localhost:8500", "/services/myapp")
02.配置隔离
a.服务隔离
// /config/service-a
// /config/service-b
03.动态配置
a.热更新
viper.WatchRemoteConfig()
04.配置同步
a.版本管理
// 配置版本控制
6.5 最佳实践
01.配置分层
a.分层结构
// 1. 默认配置 (SetDefault)
// 2. 配置文件 (ReadInConfig)
// 3. 环境变量 (AutomaticEnv)
// 4. 命令行 (BindPFlags)
02.敏感信息
a.安全实践
// 不提交密码到代码库
// 使用环境变量
viper.BindEnv("db.password", "DB_PASSWORD")
03.配置验证
a.启动检查
func ValidateConfig() error {
required := []string{"server.port", "database.host"}
for _, key := range required {
if !viper.IsSet(key) {
return fmt.Errorf("%s is required", key)
}
}
return nil
}
04.文档管理
a.配置文档
// config.example.yaml - 配置示例
// README.md - 配置说明
7 实战案例
7.1 Web应用配置
01.应用配置
a.完整配置
type Config struct {
Server struct {
Port int
Host string
Mode string
}
Log struct {
Level string
Output string
}
}
viper.Unmarshal(&config)
02.数据库配置
a.数据库连接
type DatabaseConfig struct {
Host string
Port int
User string
Password string
MaxConnections int
}
viper.UnmarshalKey("database", &dbConfig)
03.缓存配置
a.Redis配置
redisHost := viper.GetString("redis.host")
redisPort := viper.GetInt("redis.port")
04.第三方服务
a.OSS配置
ossEndpoint := viper.GetString("oss.endpoint")
ossAccessKey := viper.GetString("oss.access_key")
7.2 微服务配置
01.服务注册
a.服务信息
serviceName := viper.GetString("service.name")
servicePort := viper.GetInt("service.port")
02.配置中心
a.远程配置
viper.AddRemoteProvider("consul", "localhost:8500", "/config/myservice")
viper.WatchRemoteConfig()
03.环境隔离
a.多环境
env := os.Getenv("ENV")
viper.SetConfigName(fmt.Sprintf("config.%s", env))
04.配置管理
a.版本控制
// Git管理配置文件
7.3 多环境部署
01.环境配置
a.base + env
viper.SetConfigName("config.base")
viper.ReadInConfig()
env := os.Getenv("APP_ENV")
viper.SetConfigName("config." + env)
viper.MergeInConfig()
02.配置文件
a.文件结构
// config.base.yaml - 通用配置
// config.dev.yaml - 开发环境
// config.test.yaml - 测试环境
// config.prod.yaml - 生产环境
03.部署流程
a.配置检查
if err := ValidateConfig(); err != nil {
log.Fatal("配置验证失败:", err)
}
04.最佳实践
a.CI/CD集成
// 在CI/CD中设置环境变量
// export APP_ENV=prod
7.4 配置管理
01.配置版本
a.Git管理
// 配置文件纳入Git版本控制
// .gitignore 中排除敏感配置
02.配置审计
a.变更记录
// 记录配置变更历史
viper.OnConfigChange(func(e fsnotify.Event) {
log.Printf("配置变更: %s", e.Name)
})
03.配置备份
a.定期备份
// 备份配置文件
04.配置监控
a.变更告警
// 配置变更通知
7.5 安全实践
01.敏感信息
a.安全存储
// .gitignore
config.prod.yaml
*.secret
// 使用环境变量
viper.BindEnv("db.password", "DB_PASSWORD")
viper.BindEnv("api.secret", "API_SECRET")
02.访问控制
a.权限管理
// 配置文件权限
// chmod 600 config.prod.yaml
03.加密传输
a.TLS配置
viper.AddSecureRemoteProvider("etcd", "127.0.0.1:4001", "/config/app", "/path/cert.pem")
04.合规要求
a.数据保护
// 遵守GDPR、等保等合规要求
// 加密存储敏感数据