Listen for events and forward to external security scanning services.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

viper.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/nate-johnston/viper"
  5. )
  6. // ViperConfig holds information per config item. If an Default
  7. // is not set then it is assumed that the value is Required.
  8. // NOTE: You can not set a default on a nested value. i.e. a value
  9. // within a has in a json or yaml file. (nested.value) you can
  10. // set nested values as required.
  11. type ViperConfig struct {
  12. Key string // The config key that is required.
  13. Default interface{} // Default Value to set.
  14. Alias []string // Any key Aliases that should be registered
  15. Description string // Description of the config.
  16. }
  17. // InitViper with the passed path and config.
  18. func InitViper(path string, viperConfigs []ViperConfig) error {
  19. viper.SetConfigFile(path)
  20. if err := viper.ReadInConfig(); err != nil {
  21. return err
  22. }
  23. if err := ValidateConfig(viperConfigs); err != nil {
  24. return err
  25. }
  26. return nil
  27. }
  28. // ValidateConfig will check the defined var ViperConfigs []ViperConfig and validate
  29. // the existances of the required keys, and set defaults for all keys where defaults are
  30. // defined.
  31. func ValidateConfig(viperConfigs []ViperConfig) error {
  32. var errs []error
  33. for _, rc := range viperConfigs {
  34. if rc.Default == nil && viper.Get(rc.Key) == nil {
  35. errs = append(errs, fmt.Errorf("Key: %s, Description: %s", rc.Key, rc.Description))
  36. } else {
  37. viper.SetDefault(rc.Key, rc.Default)
  38. }
  39. if len(rc.Alias) > 0 {
  40. for _, a := range rc.Alias {
  41. viper.RegisterAlias(a, rc.Key)
  42. }
  43. }
  44. }
  45. if len(errs) > 0 {
  46. return fmt.Errorf("Required Configuration Missing: %v", errs)
  47. }
  48. return nil
  49. }