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
Missing property error
config.<field name>
? – Winstonwinstonnviper.Unmarshal()
, I would guess that that's the whole idea behind this library which is to simplify the code. – Tune