From d8a3d0d61b5473550ce406385459a9fd1878d5f2 Mon Sep 17 00:00:00 2001 From: paologaleotti Date: Tue, 9 Jul 2024 20:30:47 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20better=20env=20variable=20h?= =?UTF-8?q?andling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/api/env.go | 14 +++----------- internal/api/init.go | 2 +- pkg/util/env.go | 13 +++++++++++-- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/internal/api/env.go b/internal/api/env.go index 1945b33..88c671c 100644 --- a/internal/api/env.go +++ b/internal/api/env.go @@ -6,16 +6,8 @@ type EnvConfig struct { Environment string } -var envVarMappings = util.EnvMapping{ - "ENVIRONMENT": &env.Environment, -} - -var env = &EnvConfig{} - -func InitEnv() *EnvConfig { - for key, goVar := range envVarMappings { - *goVar = util.GetEnvOrPanic(key) +func InitEnv() EnvConfig { + return EnvConfig{ + Environment: util.GetEnvOrDefault("ENVIRONMENT", "dev"), } - - return env } diff --git a/internal/api/init.go b/internal/api/init.go index 766f8d1..b84d20c 100644 --- a/internal/api/init.go +++ b/internal/api/init.go @@ -22,7 +22,7 @@ func InitService() http.Handler { router.Use(middleware.Recoverer) router.Use(httpcore.LoggerMiddleware) - // env := api.InitEnv() // get typed environment + // env := InitEnv() // get typed environment controller := handlers.NewApiController() applyRoutes(router, controller) diff --git a/pkg/util/env.go b/pkg/util/env.go index 2d4a7fa..4f8b97b 100644 --- a/pkg/util/env.go +++ b/pkg/util/env.go @@ -2,8 +2,7 @@ package util import "os" -type EnvMapping map[string]*string - +// GetEnvOrPanic returns the value of the environment variable with the given key. func GetEnvOrPanic(key string) string { value := os.Getenv(key) if value == "" { @@ -11,3 +10,13 @@ func GetEnvOrPanic(key string) string { } return value } + +// GetEnvOrDefault returns the value of the environment variable with the given key, +// or a default value if the environment variable is not set. +func GetEnvOrDefault(key, defaultValue string) string { + value := os.Getenv(key) + if value == "" { + return defaultValue + } + return value +}