名称: viper-go-配置设置 描述: 为Go配置管理设置Viper,支持文件、环境变量和命令行标志绑定。 允许工具: 读取、写入、编辑、Bash、Glob、Grep
Viper Go 配置设置
为Go配置管理设置Viper。
生成的模式
package config
import (
"github.com/spf13/viper"
"github.com/spf13/cobra"
)
type Config struct {
Server 服务器配置 `mapstructure:"server"`
Database 数据库配置 `mapstructure:"database"`
}
type ServerConfig struct {
Host 字符串 `mapstructure:"host"`
Port 整数 `mapstructure:"port"`
}
func InitConfig(cfgFile 字符串) (*Config, 错误) {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME/.myapp")
}
viper.AutomaticEnv()
viper.SetEnvPrefix("MYAPP")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return nil, err
}
}
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return nil, err
}
return &cfg, nil
}
目标流程
- 配置管理系统
- 命令行应用程序引导