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.

85 lines
2.2 KiB

  1. package yamlsettings_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "testing"
  6. "git.kirsle.net/go/yamlsettings"
  7. )
  8. func TestLoadReaders(t *testing.T) {
  9. type Settings struct {
  10. Databases struct {
  11. PrimarySQL struct {
  12. User string `yaml:"user"`
  13. Passwd string `yaml:"passwd"`
  14. Host string `yaml:"host"`
  15. DB string `yaml:"db"`
  16. Compress bool `yaml:"compress"`
  17. Engine string `yaml:"engine"`
  18. } `yaml:"primary_sql"`
  19. Redis struct {
  20. Host string `yaml:"redis_host"`
  21. Port int `yaml:"redis_port"`
  22. } `yaml:"redis"`
  23. } `yaml:"databases"`
  24. AppConfig struct {
  25. Debug bool `yaml:"DEBUG"`
  26. SecretKey string `yaml:"SECRET_KEY"`
  27. } `yaml:"app_config"`
  28. DebugSQL bool `yaml:"debug_sql"`
  29. DebugProfiler bool `yaml:"debug_profiler"`
  30. }
  31. // The defaults.yml file you can commit to version control,
  32. // it's used as the template config that contains all options,
  33. // has sensible defaults where possible or "CHANGE_ME" where not.
  34. var (
  35. defaultsYaml = bytes.NewBuffer([]byte(`---
  36. # Program Defaults, do not edit this file!!!
  37. # All values should be overridden in the settings.yml file.
  38. databases:
  39. primary_sql:
  40. user: my_user
  41. passwd: password_here
  42. host: db-bouncer-01.postgres.com:5432
  43. db: postgres
  44. compress: true
  45. engine: postgresql2
  46. redis:
  47. redis_host: 127.0.0.1
  48. redis_port: 6379
  49. app_config:
  50. DEBUG: false
  51. SECRET_KEY: hard key to guess and keep values secret
  52. debug_sql: false
  53. debug_profiler: false`))
  54. settingsYaml = bytes.NewBuffer([]byte(`---
  55. databases:
  56. primary_sql:
  57. user: root
  58. passwd: god
  59. redis:
  60. redis_host: redis.service.com
  61. app_config:
  62. DEBUG: true
  63. SECRET_KEY: sdfasjksdfASFAS23423f@#$%!$#VR@%UQ%
  64. debug_sql: true`))
  65. )
  66. // Load the defaults and the optional settings file.
  67. // yamlsettings.LoadFiles("defaults.yml", "settings.yml", &config)
  68. var config Settings
  69. yamlsettings.LoadReaders(defaultsYaml, settingsYaml, &config)
  70. fmt.Printf("Redis host: %s\n", config.Databases.Redis.Host)
  71. fmt.Printf("Secret: %s\n", config.AppConfig.SecretKey)
  72. // Load from yaml files on disk.
  73. yamlsettings.LoadFiles("example/defaults.yml", "example/settings.yml", &config)
  74. fmt.Printf("Redis host: %s\n", config.Databases.Redis.Host)
  75. }