Skip to content

Environment variables

Environment variables are key‑value pairs that configure the operating system environment. In Go, use os.Getenv to read them, os.Setenv to set them, and os.Unsetenv to delete them.

Read the HOME variable and a custom APP_MODE variable.

package main
import (
"fmt"
"os"
)
func main() {
home := os.Getenv("HOME")
fmt.Println("Home:", home)
mode := os.Getenv("APP_MODE")
if mode == "" {
mode = "development"
}
fmt.Println("Mode:", mode)
// Lookup with ok
if val, ok := os.LookupEnv("PATH"); ok {
fmt.Println("PATH exists")
}
}
Terminal window
Home: /home/user
Mode: development
PATH exists