如何解决如何在Viper中设置必填字段?
我使用Viper https://github.com/spf13/viper在GO应用程序中管理项目配置。 还将配置值解编为结构。
var config c.Configuration // Configuration is my configuration struct
err := viper.Unmarshal(&config)
当我错过.yml配置文件中的某些配置时,在拆组期间不会抛出任何错误(如我所猜)。
那么我该如何强制实施所有配置?如果struct中的任何字段在yaml中都没有值,我想查看错误。
解决方法
您可以将 validator package 与 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)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。