.env.go.local
To get the most out of .env.go.local , follow these best practices:
go get github.com/joho/godotenv
# .env.go.local DB_HOST=localhost DB_USER=admin DB_PASSWORD=supersecretpassword API_KEY=local_debug_key PORT=8080 Use code with caution. Step 2: Update .gitignore
: You should almost always add *.local or .env.go.local to your .gitignore file to ensure your private secrets never reach your shared repository.
fmt.Printf("Starting server on port %s with DB user: %s\n", port, dbUser) .env.go.local
func loadConfig() (*Config, error) // Load environment files if err := godotenv.Load(".env", ".env.local"); err != nil && !os.IsNotExist(err) return nil, fmt.Errorf("failed to load env files: %w", err)
This leads you to environment variables, a Unix-born standard where your operating system stores key-value pairs outside your application code. In Go, you can access these via os.Getenv("DB_PASS") . But now you have another problem: manually exporting a dozen variables in your terminal session every time you open a new one is tedious and error-prone.
This pattern shines in multi-environment setups, where you might have separate overrides for development, testing, staging, and production.
os.Setenv is not safe for concurrent use, and attempting to use environment variables as a runtime configuration store can lead to unpredictable behavior. To get the most out of
For example, a Go web application might store its database connection string in an environment variable named DATABASE_URL . The base .env file could contain DATABASE_URL=postgres://localhost:5432/app_dev . A developer working on a feature branch might need to connect to a different local database, so they create an .env.go.local with DATABASE_URL=postgres://localhost:5433/app_feature . When the application starts, it loads .env first and then .env.go.local , resulting in the final value being the developer's custom URL.
Let's say you're building a web application that uses a database. In your .env file, you have the following environment variables:
# Standard environment files .env.local .env.development.local .env.test.local .env.production.local # Go-specific local environment overrides .env.go.local Use code with caution. 2. Ship a .env.example File
return godotenv.Load(".env", ".env.local") In Go, you can access these via os
: Contains default configuration values shared across the entire team (e.g., app ports, public API URLs). This file is committed to version control.
For this example, we'll use the popular godotenv library because of its simplicity and widespread adoption.
Using a .env.go.local file is a simple yet effective way to manage local environment variables in your Go applications. By separating local environment variables from shared ones, you can simplify your development workflow and reduce the risk of configuration errors.