env.dev

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:

Loading…

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.

Was this helpful?

Stay up to date

Get notified about new guides, tools, and cheatsheets.