A config file manager for Go that uses a defaults and overrides file.
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.

51 lines
1.1 KiB

  1. package yamlsettings
  2. import (
  3. "io"
  4. "os"
  5. "gopkg.in/yaml.v2"
  6. )
  7. // LoadFiles marshals your app settings from the default.yml overridden
  8. // by the settings.yml file.
  9. func LoadFiles(defaultsFile, settingsFile string, v interface{}) error {
  10. // Read the defaults file.
  11. if err := LoadFile(defaultsFile, v); err != nil {
  12. return err
  13. }
  14. // Read the settings.yml. It's OK if it doesn't exist.
  15. if err := LoadFile(settingsFile, v); err != nil && !os.IsNotExist(err) {
  16. return err
  17. }
  18. return nil
  19. }
  20. // LoadFile opens and marshals YAML settings from a single config file.
  21. func LoadFile(filename string, v interface{}) error {
  22. fh, err := os.Open(filename)
  23. if err != nil {
  24. return err
  25. }
  26. dec := yaml.NewDecoder(fh)
  27. return dec.Decode(v)
  28. }
  29. // LoadReaders marshals your app settings from the defaults and settings
  30. // readers, so you can feed in YAML data from sources other than files
  31. // on disk.
  32. func LoadReaders(defaults, settings io.Reader, v interface{}) error {
  33. if defaults != nil {
  34. if err := yaml.NewDecoder(defaults).Decode(v); err != nil {
  35. return err
  36. }
  37. }
  38. if settings != nil {
  39. return yaml.NewDecoder(settings).Decode(v)
  40. }
  41. return nil
  42. }