From 203ffd8862ec78153d41b0fcd153d560967a2dda Mon Sep 17 00:00:00 2001 From: Alexandre Pauwels Date: Thu, 5 Oct 2023 18:04:14 +0100 Subject: [PATCH] fix: adds appropriate env-based switch for config file location --- go.mod | 2 +- main.go | 25 ++++++++++++++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 6d34625..fa4a97b 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.21.1 require ( github.com/ajpauwels/pit-of-vipers v1.0.3 + github.com/spf13/viper v1.10.1 go.uber.org/zap v1.26.0 ) @@ -17,7 +18,6 @@ require ( github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/spf13/viper v1.10.1 // indirect github.com/subosito/gotenv v1.2.0 // indirect go.uber.org/multierr v1.10.0 // indirect golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect diff --git a/main.go b/main.go index a2e9fe6..74afac8 100644 --- a/main.go +++ b/main.go @@ -11,7 +11,9 @@ import ( "strings" viperpit "github.com/ajpauwels/pit-of-vipers" + "github.com/spf13/viper" "go.uber.org/zap" + "os" ) type SlackConfig struct { @@ -103,13 +105,30 @@ func main() { } defer logger.Sync() - // Load configuration - vpCh, errCh := viperpit.NewFromPathsAndName([]string{"./config"}, "base") + // Load env-specific configuration + env := os.Getenv("APPCFG_meta_env") + configPath := "./config" + if len(env) <= 0 { + env = "local" + } + if env != "local" { + configPath = "/etc/slack-bot/config" + } + + // Create viper instances for base and env-specific config files + baseViper := viper.New() + baseViper.AddConfigPath(configPath) + baseViper.SetConfigName("base") + envViper := viper.New() + envViper.AddConfigPath(configPath) + envViper.SetConfigName(env) + + vpCh, errCh := viperpit.New([]*viper.Viper{baseViper, envViper}) for { select { case vp := <-vpCh: // Workaround to add ENV prefix and be able to unmarshal env-provided values - vp.SetEnvPrefix("SERVICE") + vp.SetEnvPrefix("APPCFG") vp.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) for _, key := range vp.AllKeys() { val := vp.Get(key)