loader.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package config
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "gopkg.in/yaml.v3"
  8. )
  9. var config = Config{
  10. Port: 8080,
  11. Sslport: 8443,
  12. ServiceURL: "http://127.0.0.1",
  13. HealthCheck: HealthCheck{
  14. Period: 30,
  15. },
  16. }
  17. // File the config file
  18. var File = "config/service.yaml"
  19. // Get returns loaded config
  20. func Get() Config {
  21. return config
  22. }
  23. // Load loads the config
  24. func Load() error {
  25. _, err := os.Stat(File)
  26. if err != nil {
  27. return err
  28. }
  29. data, err := ioutil.ReadFile(File)
  30. if err != nil {
  31. return fmt.Errorf("can't load config file: %s", err.Error())
  32. }
  33. err = yaml.Unmarshal(data, &config)
  34. if err != nil {
  35. return fmt.Errorf("can't unmarshal config file: %s", err.Error())
  36. }
  37. readSecret()
  38. value, _ := yaml.Marshal(config)
  39. log.Printf("using configfile %s. \nconfiguration:\n%s\n", File, string(value))
  40. return nil
  41. }
  42. func readSecret() error {
  43. secretFile := config.SecretFile
  44. if secretFile != "" {
  45. data, err := ioutil.ReadFile(secretFile)
  46. if err != nil {
  47. return fmt.Errorf("can't load secret file: %s", err.Error())
  48. }
  49. var secretConfig Secret = Secret{}
  50. err = yaml.Unmarshal(data, &secretConfig)
  51. if err != nil {
  52. return fmt.Errorf("can't unmarshal secret file: %s", err.Error())
  53. }
  54. mergeSecret(secretConfig)
  55. }
  56. return nil
  57. }
  58. func mergeSecret(secret Secret) {
  59. config.MongoDB.Username = secret.MongoDB.Username
  60. config.MongoDB.Password = secret.MongoDB.Password
  61. }