← Back to Go Course | Chapter 13: File IO & OS | Lesson 6 of 7

Environment Variables

An environment variable is a setting stored outside your program, in the operating system's environment, that your program can peek at to learn things like configuration without hardcoding them.

Reading an Environment Variable

os.Getenv retrieves the value of a named environment variable, returning an empty string if it isn't set -- simple, but it can't distinguish 'not set' from 'set to empty'.

Example: Reading an Environment Variable

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	os.Setenv("APP_MODE", "production")
	mode := os.Getenv("APP_MODE")
	fmt.Println("running in mode:", mode)
}

Checking If a Variable Is Set

os.LookupEnv returns both the value and a boolean indicating whether the variable was actually present, letting you distinguish an intentionally empty value from a missing one.

Note: Use LookupEnv whenever an empty string is a meaningfully different case from unset.

Example: Checking If a Variable Is Set

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	val, ok := os.LookupEnv("MISSING_VAR")
	fmt.Println("value:", val, "was set:", ok)
}

Setting a Default When Unset

A common pattern is reading a configuration value from the environment and falling back to a sensible default if it isn't set, avoiding a program crash for optional settings.

Example: Setting a Default When Unset

markup
package main

import (
	"fmt"
	"os"
)

func getEnvOrDefault(key, fallback string) string {
	if val, ok := os.LookupEnv(key); ok {
		return val
	}
	return fallback
}

func main() {
	port := getEnvOrDefault("PORT", "8080")
	fmt.Println("using port:", port)
}
Common Mistakes
  1. Assuming os.Getenv returns an error for a missing variable -- it silently returns an empty string instead.
  2. Not using os.LookupEnv when you need to distinguish an unset variable from one deliberately set to an empty string.
  3. Hardcoding sensitive values (like API keys) directly in source code instead of reading them from the environment.
Chapter Summary
  • os.Getenv(name) reads an environment variable, returning an empty string if it's unset.
  • os.LookupEnv(name) additionally returns a boolean indicating whether the variable was actually set.
  • os.Setenv sets an environment variable for the current process (and its children).
  • Environment variables are a common way to pass configuration into a program without hardcoding it.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.