Skip to content

Commit

Permalink
feat: ✨ better env variable handling
Browse files Browse the repository at this point in the history
  • Loading branch information
paologaleotti committed Jul 9, 2024
1 parent 1e197d7 commit d8a3d0d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
14 changes: 3 additions & 11 deletions internal/api/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion internal/api/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 11 additions & 2 deletions pkg/util/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,21 @@ 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 == "" {
panic(key + " environment variable is not set")
}
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
}

0 comments on commit d8a3d0d

Please sign in to comment.