Skip to content

Go Environment Variables

Environment variables are a standard way to configure applications without hardcoding values. Go's os package provides the tools to read and set them.

1. Getting Variables

Use os.Getenv to get a value. If the variable isn't set, it returns an empty string.

package main

import (
    "fmt"
    "os"
)

func main() {
    // 1. Get a common system variable
    fmt.Println("Shell:", os.Getenv("SHELL"))

    // 2. Get a variable with a default value fallback
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
    fmt.Println("Port:", port)
}

2. Checking if a Variable Exists

Use os.LookupEnv if you need to know if a variable was actually defined (it could be defined as an empty string).

1
2
3
4
5
6
val, exists := os.LookupEnv("MY_SECRET")
if !exists {
    fmt.Println("MY_SECRET is not set!")
} else {
    fmt.Println("Value:", val)
}

3. Setting and Unsetting

1
2
3
4
5
// Set a variable
os.Setenv("FOO", "1")

// Unset (remove) a variable
os.Unsetenv("FOO")

4. Listing All Variables

os.Environ() returns a slice of strings in the format KEY=VALUE.

1
2
3
for _, e := range os.Environ() {
    fmt.Println(e)
}

Why use Environment Variables?

  1. Twelve-Factor App: It's a best practice to store configuration in the environment, keeping code separate from dynamic settings.
  2. Security: Never hardcode API keys or database passwords in your code. Set them as environment variables instead.
  3. Docker/Kubernetes: Modern deployment tools are designed to inject configuration via the environment.