Environment Variables
In this page:
Reading an Environment Variable
os.Getenv retrieves the value of a named environment variable, returning an empty string if it isn't set -- simple, but it can't distinguish 'not set' from 'set to empty'.
Example: Reading an Environment Variable
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("APP_MODE", "production")
mode := os.Getenv("APP_MODE")
fmt.Println("running in mode:", mode)
}
Login to try C/C++/Java/PHP code in the editor
Checking If a Variable Is Set
os.LookupEnv returns both the value and a boolean indicating whether the variable was actually present, letting you distinguish an intentionally empty value from a missing one.
Note: Use LookupEnv whenever an empty string is a meaningfully different case from unset.
Example: Checking If a Variable Is Set
package main
import (
"fmt"
"os"
)
func main() {
val, ok := os.LookupEnv("MISSING_VAR")
fmt.Println("value:", val, "was set:", ok)
}
Login to try C/C++/Java/PHP code in the editor
Setting a Default When Unset
A common pattern is reading a configuration value from the environment and falling back to a sensible default if it isn't set, avoiding a program crash for optional settings.
Example: Setting a Default When Unset
package main
import (
"fmt"
"os"
)
func getEnvOrDefault(key, fallback string) string {
if val, ok := os.LookupEnv(key); ok {
return val
}
return fallback
}
func main() {
port := getEnvOrDefault("PORT", "8080")
fmt.Println("using port:", port)
}
Login to try C/C++/Java/PHP code in the editor
- Assuming os.Getenv returns an error for a missing variable -- it silently returns an empty string instead.
- Not using os.LookupEnv when you need to distinguish an unset variable from one deliberately set to an empty string.
- Hardcoding sensitive values (like API keys) directly in source code instead of reading them from the environment.
- os.Getenv(name) reads an environment variable, returning an empty string if it's unset.
- os.LookupEnv(name) additionally returns a boolean indicating whether the variable was actually set.
- os.Setenv sets an environment variable for the current process (and its children).
- Environment variables are a common way to pass configuration into a program without hardcoding it.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: