Go Environment Variables
Environment variables are a standard way to configure applications without hardcoding values. Go's os package provides the tools to read and set them.
1. Getting Variables
Use os.Getenv to get a value. If the variable isn't set, it returns an empty string.
2. Checking if a Variable Exists
Use os.LookupEnv if you need to know if a variable was actually defined (it could be defined as an empty string).
3. Setting and Unsetting
4. Listing All Variables
os.Environ() returns a slice of strings in the format KEY=VALUE.
Why use Environment Variables?
- Twelve-Factor App: It's a best practice to store configuration in the environment, keeping code separate from dynamic settings.
- Security: Never hardcode API keys or database passwords in your code. Set them as environment variables instead.
- Docker/Kubernetes: Modern deployment tools are designed to inject configuration via the environment.