.env.go.local -
package main
Immediately prevent this file from being pushed to Git. # .gitignore .env.go.local Use code with caution. Step 3: Install godotenv Use the popular godotenv library to load the file: go get ://github.com Use code with caution. Step 4: Load and Use in Go
package main import ( "fmt" "log" "os" "://github.com" ) func init() // Define the loading order from high priority to low priority envFiles := []string".env.go.local", ".env.local", ".env" for _, file := range envFiles // We use Load instead of Overload to ensure system env vars are respected err := godotenv.Load(file) if err != nil // It is okay if some files do not exist locally continue func main() // Retrieve a variable dbUser := os.Getenv("DB_USER") dbPass := os.Getenv("DB_PASSWORD") port := os.Getenv("APP_PORT") if port == "" port = "8080" // Fallback default fmt.Printf("Application starting on port %s...\n", port) fmt.Printf("Database User: %s\n", dbUser) // Never print passwords in production logs! This is for local demonstration only. fmt.Printf("Database Password: %s\n", dbPass) Use code with caution. Best Practices for Git and Production Update .gitignore Immediately
The two most common libraries are joho/godotenv and spf13/viper . Method 1: Using godotenv (The Simple Approach) .env.go.local
: In a standard loading hierarchy, values in .env.go.local should override values defined in .env or .env.development . However, actual system environment variables set in your terminal should typically override everything. Implementing .env.go.local in a Go Application
.env.local file is a local configuration file used to store environment-specific variables—such as database credentials or API keys—without committing them to version control. In Go, while the standard library's
import ( "log" "os" "path/filepath"
Using .env.go.local is a small change to your development workflow that provides significant benefits in security, team coordination, and environment portability. By keeping machine-specific configurations out of version control, you create a more secure and reliable development experience for your Go applications.
"github.com/joho/godotenv"
: As we've touched on, the most critical rule is to never commit sensitive information like passwords, API keys, or tokens to version control . A file like .env.go.local , which is typically added to your .gitignore file, is not tracked by Git. It acts as a safe vault for your local secrets, ensuring they stay on your machine and don't end up in a public code repository. Your database.go file can freely call os.Getenv("DB_PASSWORD") , knowing that secret will be safely injected at runtime, not stored in plain sight in your codebase. package main Immediately prevent this file from being
Connecting to Production Database... Connection Established. Migration Successful.
The running service will use LOG_LEVEL=debug and REDIS_ADDR=localhost:6380 , but still take PORT and DB_DSN from .env .