.env.go.local
func getenv(key, defaultValue string) string val := os.Getenv(key) if val == "" return defaultValue
: Always provide default values in your code for non-sensitive variables in case they are missing from the environment. Validation
A common, robust hierarchy looks like this (from lowest priority to highest priority):
: A Go-specific baseline file. It defines standard settings unique to the Go implementation of a service (useful in polyglot monorepos). .env.go.local
// You can even add validation here. println("⚠️ Running in LOCAL mode with development config.")
: Always maintain a .env.example or .env.go.example file in your repository. This file should contain the keys but leave the values blank, serving as a blueprint for onboarding new developers.
func loadConfig() defaults, _ := godotenv.Read(".env") overrides, _ := godotenv.Read(".env.go.local") for k, v := range overrides defaults[k] = v func getenv(key, defaultValue string) string val := os
// Load returns the configuration. Local file will augment this. func Load() AppConfig return AppConfig Port: getEnvAsInt("PORT", 8080), Debug: getEnvAsBool("DEBUG", false), DBURL: os.Getenv("DATABASE_URL"),
First, install it:
No changes committed. No fighting with git. No environment pollution. // You can even add validation here
DB_HOST=localhost DB_PORT=5432 DB_USER=myuser DB_PASSWORD=mypassword
import ( "log"