go - 如何在 Viper 中设置必需的配置字段?
问题描述
我使用 Viper https://github.com/spf13/viper在我的 GO 应用程序中管理项目配置,以及将配置值解组到结构。
var config c.Configuration // Configuration is my configuration struct
err := viper.Unmarshal(&config)
当我错过 .yml 配置文件中的一些配置时,它在 Unmarshaling 期间不会抛出任何错误(正如我所猜测的)。
那么我怎样才能强制实现所有配置呢?如果 struct 中的任何字段在 yaml 中没有值,我想查看错误。
解决方案
您可以将验证器包与 viper 集成在一起,以便您可以检查任何缺少的配置。附上我的工作代码的代码片段和配置屏幕截图。
package config
import (
"github.com/go-playground/validator/v10"
"github.com/spf13/viper"
"log"
)
type Configuration struct {
Server struct {
Application string `yaml:"application" validate:"required"`
} `yaml:"server"`
}
var config Configuration
func GetConfig() *Configuration {
return &config
}
func init() {
vp := viper.New()
vp.SetConfigName("config") // name of config file (without extension)
vp.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
vp.AddConfigPath(".")
if err := vp.ReadInConfig(); err!=nil {
log.Fatalf("Read error %v", err)
}
if err := vp.Unmarshal(&config); err!=nil {
log.Fatalf("unable to unmarshall the config %v", err)
}
validate := validator.New()
if err := validate.Struct(&config); err!=nil{
log.Fatalf("Missing required attributes %v\n", err)
}
}
推荐阅读
- pytest - pytest:使用假设时的monkeypatch
- android - 如何一次用 @dimen/50_dp 替换所有 dp 值,例如 50dp?
- automation - 如何从机器人框架中获取给定字符串中的子字符串?
- jenkins - Jenkins DSL,传递的字符串不多 Enum => `No enum constant'
- git - Git 列出包含字符串的提交,其中包含该字符串的更改行周围有差异
- php - 带有 PKCS7 填充的 AES 256
- apache-spark - 将 sql 查询转换为等效的 spark 查询
- python - 使用“嵌套”创建一个脚本,首先打印列表中的单词,然后打印每个字母
- python - 在 PyQT 中单击按钮后的 Msg_box
- android - 无法在 OnCreate 中将视图添加到 LinearLayout