env.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package helpers
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/spf13/viper"
  6. )
  7. var subViper *viper.Viper = nil
  8. var currentStage = ""
  9. const (
  10. ENVFILENAME = "metarare_envs"
  11. ENVFILEEXT = "yaml"
  12. )
  13. func getStage() string {
  14. if currentStage != "" {
  15. return currentStage
  16. }
  17. if _, err := os.Stat(fmt.Sprintf("%s.%s", ENVFILENAME, ENVFILEEXT)); !os.IsNotExist(err) {
  18. vv := viper.New()
  19. vv.SetConfigName(ENVFILENAME)
  20. vv.SetConfigType(ENVFILEEXT)
  21. vv.AddConfigPath(".")
  22. err := vv.ReadInConfig()
  23. if err != nil {
  24. panic(fmt.Errorf("fatal error config file: %s \n", err))
  25. }
  26. currentStage = vv.GetString("stage")
  27. }
  28. return currentStage
  29. }
  30. func LoadEnvs() *viper.Viper {
  31. if subViper != nil {
  32. return subViper
  33. }
  34. stage := getStage()
  35. viper.SetConfigFile(ENVFILEEXT)
  36. fmt.Printf("Curretn Stage: %s\n", stage)
  37. if stage == "dev" {
  38. fmt.Println("Load env variables from local. ")
  39. viper.AddConfigPath(".")
  40. viper.SetConfigName(ENVFILENAME)
  41. if err := viper.ReadInConfig(); err != nil {
  42. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  43. }
  44. } else if stage == "prod" {
  45. viper.AddConfigPath(".")
  46. viper.SetConfigName(ENVFILENAME)
  47. if err := viper.ReadInConfig(); err != nil {
  48. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  49. }
  50. } else if stage == "fork" {
  51. fmt.Println("Load env variables from local. ")
  52. viper.AddConfigPath(".")
  53. viper.SetConfigName(ENVFILENAME)
  54. if err := viper.ReadInConfig(); err != nil {
  55. panic(fmt.Errorf("Fatal error config file: %s \n", err))
  56. }
  57. }
  58. subViper = viper.Sub(fmt.Sprintf("stage_%s", stage))
  59. return subViper
  60. }