Skip to content

Commit

Permalink
feat: config validation
Browse files Browse the repository at this point in the history
  • Loading branch information
xsteadfastx committed Nov 16, 2021
1 parent 12164cc commit efafd01
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"time"

"github.com/VictoriaMetrics/metrics"
"github.com/go-playground/validator/v10"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -47,16 +48,16 @@ var rootCmd = &cobra.Command{
// config is a struct that a config file can get unmarshaled to.
type config struct {
Exporter struct {
Listen string
Timeout time.Duration
ProcessMetrics bool `mapstructure:"process_metrics"`
Listen string `validate:"required,hostname_port"`
Timeout time.Duration `validate:"required,gt=0"`
ProcessMetrics bool `mapstructure:"process_metrics" validate:"required"`
}
Log struct {
JSON bool
Colors bool
Colors bool `validate:"required"`
}
Iperf3 struct {
Time int
Time int `validate:"required"`
}
}

Expand Down Expand Up @@ -376,6 +377,25 @@ func initConfig() {
}

log.Logger = log.With().Caller().Logger()

// Valite config.
validate := validator.New()
if err := validate.Struct(c); err != nil {
var validationErrors validator.ValidationErrors

if errors.As(err, &validationErrors) {
for _, e := range validationErrors {
log.Error().
Str("tag", e.Tag()).
Str("name", e.StructNamespace()).
Interface("value", e.Value()).
Str("kind", e.Kind().String()).
Msg("config error")
}
}

log.Fatal().Msg("config validation error")
}
}

func main() {
Expand Down

0 comments on commit efafd01

Please sign in to comment.