package helpers import ( "fmt" "os" "github.com/spf13/viper" ) var subViper *viper.Viper = nil var currentStage = "" const ( ENVFILENAME = "metarare_envs" ENVFILEEXT = "yaml" ) func getStage() string { if currentStage != "" { return currentStage } if _, err := os.Stat(fmt.Sprintf("%s.%s", ENVFILENAME, ENVFILEEXT)); !os.IsNotExist(err) { vv := viper.New() vv.SetConfigName(ENVFILENAME) vv.SetConfigType(ENVFILEEXT) vv.AddConfigPath(".") err := vv.ReadInConfig() if err != nil { panic(fmt.Errorf("fatal error config file: %s \n", err)) } currentStage = vv.GetString("stage") } return currentStage } func LoadEnvs() *viper.Viper { if subViper != nil { return subViper } stage := getStage() viper.SetConfigFile(ENVFILEEXT) fmt.Printf("Curretn Stage: %s\n", stage) if stage == "dev" { fmt.Println("Load env variables from local. ") viper.AddConfigPath(".") viper.SetConfigName(ENVFILENAME) if err := viper.ReadInConfig(); err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } } else if stage == "prod" { viper.AddConfigPath(".") viper.SetConfigName(ENVFILENAME) if err := viper.ReadInConfig(); err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } } else if stage == "fork" { fmt.Println("Load env variables from local. ") viper.AddConfigPath(".") viper.SetConfigName(ENVFILENAME) if err := viper.ReadInConfig(); err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } } subViper = viper.Sub(fmt.Sprintf("stage_%s", stage)) return subViper }