【问题标题】:How to make configuration fields required in Viper?如何在 Viper 中设置必需的配置字段?
【发布时间】:2020-09-02 16:26:23
【问题描述】:

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

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

err := viper.Unmarshal(&config)

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

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

【问题讨论】:

  • 为什么不在config.<field name> 上做 nil check 之类的?
  • @snapGeek 因为这将是手动方法,我知道例如在 node.js 中通过库是可能的。
  • 如果您已经在检查配置解析错误,为什么还要手动执行此操作。当您调用 viper.Unmarshal() 时,该库可能会返回错误,我猜这就是该库背后的全部想法,即简化代码。

标签: go yaml viper-go


【解决方案1】:

您可以将validator package 与 viper 集成在一起,以便您检查是否有任何缺失的配置。附上我的工作代码的代码 sn-p 和配置屏幕截图。

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)
    }
}

我的属性截图

缺少属性错误

【讨论】:

    猜你喜欢
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 2020-09-24
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多