登录
首页 >  Golang >  Go问答

要求在Viper中的配置字段中填写所有必填信息

来源:stackoverflow

时间:2024-03-12 14:12:25 350浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《要求在Viper中的配置字段中填写所有必填信息》,聊聊,我们一起来看看吧!

问题内容

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

1
2
3
var config c.Configuration // Configuration is my configuration struct
 
err := viper.Unmarshal(&config)

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

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


解决方案


您可以将 validator package 与 viper 集成,以便您可以检查是否有任何丢失的配置。附上我的工作代码的代码片段和配置屏幕截图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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)
    }
}

我的财产截图

缺少属性错误

今天关于《要求在Viper中的配置字段中填写所有必填信息》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>