如何使Viper中的配置字段成为必填项?

Tig*_*yan 11 yaml go viper-go

我使用 Viper https://github.com/spf13/viper来管理 GO 应用程序中的项目配置,以及将配置值解组到结构体。

var config c.Configuration // Configuration is my configuration struct

err := viper.Unmarshal(&config)
Run Code Online (Sandbox Code Playgroud)

当我错过 .yml 配置文件中的某些配置时,它在解组期间不会抛出任何错误(正如我所猜测的)。

那么我怎样才能强制实施所有配置呢?如果结构体中的任何字段在 yaml 中没有值,我想查看错误。

小智 9

您可以将验证程序包与 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的财产截图 属性配置

缺少属性错误 缺少属性错误