Retrieve the value of an environment variable, distinguishing unset from empty.
The os.LookupEnv function retrieves the value of the environment variable named by the key. Unlike os.Getenv, it returns a second boolean result that is true if the variable is set (even to the empty string) and false if the variable is not set at all.
This distinction matters for configuration: an unset variable typically means "use the default," while an explicit empty value means "override the default with nothing." Code that needs that distinction must use LookupEnv rather than Getenv.
The function is in the os package and reads the process's current environment, which is updated by os.Setenv and os.Unsetenv. It does not parse .env files; for those, use a third-party library or read the file manually.
| Name | Description | Optional |
|---|---|---|
key |
The name of the environment variable. | No |
import "os"
if val, ok := os.LookupEnv("PORT"); ok {
fmt.Println("PORT set to:", val)
} else {
fmt.Println("PORT is not set, using default 8080")
}