How to make configuration fields required in Viper?
Asked Answered
B

1

12

I use Viper https://github.com/spf13/viper for managing project configurations in my GO app, and also for Unmarshaling configuration values to a struct.

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

err := viper.Unmarshal(&config)

When I miss some configs in .yml config file it doesn't throw any error (as I had guessed) during Unmarshaling.

So how can I force to have all configs implemented? I want to see errors if any field from struct doesn't have value in yaml.

Bleeding answered 2/9, 2020 at 16:26 Comment(3)
Why not do nil check or something on the config.<field name> ?Winstonwinstonn
@Winstonwinstonn because that will be manually approach, I know for example that is possible in node.js by library.Bleeding
Why do this manually if you are already checking for configuration parsing errors. The lib could just return an error when you call viper.Unmarshal(), I would guess that that's the whole idea behind this library which is to simplify the code.Tune
K
11

You can integrate validator package along with viper, so that you can check for any missing configuration. Attaching code snippet and config screenshot of my working code.

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

My property screenshot property configuration

Missing property error Missing property error

Kook answered 2/8, 2021 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.