您可以将验证器包与 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)
}
}
我的财产截图
缺少属性错误