Enhanced config validation

This commit is contained in:
CrazyMax
2020-07-16 22:34:44 +02:00
parent e5862e4efb
commit 1c114fe60e
3 changed files with 14 additions and 33 deletions

View File

@@ -2,6 +2,8 @@ package config
import (
"encoding/json"
"os"
"path"
"github.com/crazy-max/diun/v4/internal/model"
"github.com/crazy-max/gonfig"
@@ -52,14 +54,23 @@ func Load(cfgfile string) (*Config, error) {
log.Info().Msgf("Configuration loaded from %d environment variable(s)", len(envLoader.GetVars()))
}
validate := validator.New()
if err := validate.Struct(&cfg); err != nil {
if err := cfg.validate(); err != nil {
return nil, err
}
return &cfg, nil
}
func (cfg *Config) validate() error {
if len(cfg.Db.Path) > 0 {
if err := os.MkdirAll(path.Dir(cfg.Db.Path), os.ModePerm); err != nil {
return errors.Wrap(err, "Cannot create database destination folder")
}
}
return validator.New().Struct(cfg)
}
// String returns the string representation of configuration
func (cfg *Config) String() string {
b, _ := json.MarshalIndent(cfg, "", " ")

View File

@@ -7,7 +7,7 @@ type NotifAmqp struct {
Password string `yaml:"password,omitempty" json:"password,omitempty" validate:"omitempty"`
PasswordFile string `yaml:"passwordFile,omitempty" json:"passwordFile,omitempty" validate:"omitempty,file"`
Host string `yaml:"host,omitempty" json:"host,omitempty" validate:"required"`
Port int `yaml:"port,omitempty" json:"port,omitempty" validate:"required"`
Port int `yaml:"port,omitempty" json:"port,omitempty" validate:"required,min=1"`
Queue string `yaml:"queue,omitempty" json:"queue,omitempty" validate:"required"`
Exchange string `yaml:"exchange,omitempty" json:"exchange,omitempty" validate:"omitempty"`
}

View File

@@ -1,11 +1,7 @@
package model
import (
"net/mail"
"github.com/crazy-max/diun/v4/pkg/utl"
"github.com/imdario/mergo"
"github.com/pkg/errors"
)
// NotifMail holds mail notification configuration details
@@ -36,29 +32,3 @@ func (s *NotifMail) SetDefaults() {
s.SSL = utl.NewFalse()
s.InsecureSkipVerify = utl.NewFalse()
}
// UnmarshalYAML implements the yaml.Unmarshaler interface
func (s *NotifMail) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain NotifMail
if err := unmarshal((*plain)(s)); err != nil {
return err
}
if _, err := mail.ParseAddress(s.From); err != nil {
return errors.Wrap(err, "cannot parse sender mail address")
}
if _, err := mail.ParseAddress(s.To); err != nil {
return errors.Wrap(err, "cannot parse recipient mail address")
}
if err := mergo.Merge(s, NotifMail{
Host: "localhost",
Port: 25,
SSL: utl.NewFalse(),
InsecureSkipVerify: utl.NewFalse(),
}); err != nil {
return errors.Wrap(err, "cannot set default values for mail notif")
}
return nil
}