配置管理与REST API开发实践
1. 使用Viper进行配置管理
1.1 Viper简介
Viper是Go应用程序的配置管理解决方案,允许通过多种方式为应用程序指定配置选项,包括配置文件、环境变量和命令行标志。当使用Cobra生成器创建应用程序的样板代码时,会自动启用Viper。
1.2 初始化Viper配置
在 cmd/root.go
文件中,通过 initConfig
函数初始化Viper配置:
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".pScan" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".pScan")
}
viper.Automa