Read an environment variable
Read an environment variable in Go with os.LookupEnv, which tells an unset variable from an empty one. os.Getenv returns an empty string for both.
A program reads a setting from the environment, and an empty value must mean something different from no value.
package main
import (
"fmt"
"os"
)
func main() {
for _, name := range []string{"SET_VAR", "EMPTY_VAR", "UNSET_VAR"} {
v, ok := os.LookupEnv(name)
fmt.Printf("%-9s Getenv=%q LookupEnv=(%q, %v)\n", name, os.Getenv(name), v, ok)
}
}SET_VAR=on EMPTY_VAR= go run main.goSET_VAR Getenv="on" LookupEnv=("on", true)
EMPTY_VAR Getenv="" LookupEnv=("", true)
UNSET_VAR Getenv="" LookupEnv=("", false)os.Getenv returns the empty string for a missing variable, so its result cannot tell the two cases apart. os.LookupEnv returns the value and a boolean that is true when the variable exists, even when it is empty, as the os package documentation explains. The output shows the third variable is the only one reported as not present.
On Linux, Path and PATH are different variables. For configuration with defaults, a small helper that returns the fallback only when ok is false keeps an explicit empty value working.