gpt4 book ai didi

go - 如何使 Viper 中的配置字段成为必需?

转载 作者:行者123 更新时间:2023-12-04 13:33:20 24 4
gpt4 key购买 nike

我用毒蛇 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)
}
}
我的属性(property)截图
property configuration
缺少属性错误
Missing property error

关于go - 如何使 Viper 中的配置字段成为必需?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63709710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com