Reputation: 2025
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.
Upvotes: 12
Views: 5527
Reputation: 301
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)
}
}
Upvotes: 12