11

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Tigran Babajanyan
  • 1,967
  • 1
  • 22
  • 41
  • Why not do nil check or something on the ```config.``` ? – snapGeek Sep 02 '20 at 21:00
  • 1
    @snapGeek because that will be manually approach, I know for example that is possible in node.js by library. – Tigran Babajanyan Sep 03 '20 at 10:19
  • 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. – VinGarcia Apr 19 '21 at 18:04

1 Answers1

9

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

Abinash
  • 161
  • 1
  • 7