Go Environment Variables: os.Getenv, godotenv & Viper
How to read, set, and manage environment variables in Go. Covers os.Getenv, os.LookupEnv, godotenv, Viper, envconfig, build-time variables, and testing.
Last updated:
Frequently Asked Questions
How do I read an environment variable in Go?
Use os.Getenv("KEY") which returns the value or an empty string if not set. Use os.LookupEnv("KEY") when you need to distinguish between an empty value and a missing variable — it returns both the value and a boolean.
How do I use .env files in Go?
Use the godotenv package: import "github.com/joho/godotenv" and call godotenv.Load() at the start of main(). It reads .env and sets values in the environment. Alternatively, use Viper which supports .env files alongside YAML, JSON, and TOML.
Stay up to date
Get notified about new guides, tools, and cheatsheets.
Related Cheatsheets
Cheatsheet
YAML Syntax Cheat Sheet — Scalars, Collections & Gotchas
Quick reference for YAML syntax: strings, numbers, multiline values, sequences, mappings, anchors, aliases, and common gotchas like the Norway problem.
Cheatsheet
Go (Golang) Cheat Sheet — Quick Reference
Go quick reference: types, structs, interfaces, goroutines, channels, error handling, slices, maps, and defer/panic/recover.
Related Guides
Next.js Environment Variables: Complete Guide
How Next.js handles environment variables: .env files, NEXT_PUBLIC_ prefix, server vs client access, load order, and common production errors.
The Complete .env File Syntax Reference
Definitive reference for .env file syntax: quoting rules, comments, multiline values, variable expansion, and differences across Node.js, Python, Ruby, Go, and Docker Compose.
The .env File: A Complete Guide to Environment Variables
Everything you need to know about .env files: syntax, usage across languages, best practices, and common pitfalls.