Environment Variables
Read named settings supplied to a program by its operating system.
Environment variables are named settings supplied to a running program by the operating system. They are often used for options such as a port number or operating mode. Getenv returns an empty string when a setting is absent; LookupEnv also reports whether it was set.
Use LookupEnv when an empty value differs from a missing value. This example reads a non-secret setting without printing its value.
package main
import (
"fmt"
"os"
)
func main() {
mode, ok := os.LookupEnv("APP_MODE")
if !ok {
fmt.Println("APP_MODE is not set")
return
}
fmt.Println("APP_MODE is set:", mode)
}In production
Check required settings when the program starts and report missing names without printing secret values. Setenv changes a setting for programs started later by this program. Set values before starting those other programs.
Enjoyed this? Get more software craft delivered to your inbox.