Go environment variables let you configure a program from the outside. So the same binary runs on your laptop, in testing and in production. In this post, you will read variables safely, add defaults, convert text to numbers and build a small config loader. Each idea comes with a short example.
Every value arrives as text, so the strconv helpers from Go strings explained with examples will be useful. We will also return clear errors, just like in error handling in Go for beginners.
What Are Go Environment Variables?
An environment variable is a named piece of text that the operating system passes to every program it starts. For example, PORT=8080 or DATABASE_URL=postgres://localhost/shop. Your program reads Go environment variables at startup.
Think of a hotel key card. The room is the same for every guest, but each card opens it with different settings. Similarly, one compiled program can behave differently on each server.
This idea comes from the twelve-factor app guidelines. In short, keep configuration out of your code, so you never commit passwords to Git.
Reading a Variable: Getenv vs LookupEnv
fmt.Printf("%q\n", os.Getenv("NOT_SET")) // ""
v, ok := os.LookupEnv("NOT_SET")
fmt.Printf("%q %v\n", v, ok) // "" false
os.Getenv returns an empty string when a variable is missing. However, it cannot tell “missing” apart from “set to empty”. So use os.LookupEnv when that difference matters, because it also returns a boolean.
A Helper with a Default
func getEnv(key, fallback string) string {
if v, ok := os.LookupEnv(key); ok {
return v
}
return fallback
}
This tiny helper for Go environment variables appears in almost every service. It returns the real value when one exists, or a sensible default otherwise.
Converting Go Environment Variables to Numbers
Every value is a string, even PORT=9000. Therefore, convert it with strconv and check the error.
port, err := strconv.Atoi(getEnv("PORT", "8080"))
if err != nil {
return Config{}, fmt.Errorf("PORT must be a number: %w", err)
}
Similarly, use strconv.ParseBool for flags like DEBUG=true and time.ParseDuration for values like TIMEOUT=5s.
Building a Config Loader
The best pattern is to read everything once at startup into a struct. The diagram below shows the flow from the environment to your app.

Load reads each variable, applies defaults, converts types and validates required values before main starts the app.
type Config struct {
Port int
DBURL string
Debug bool
Timeout time.Duration
}
func Load() (Config, error) {
port, err := strconv.Atoi(getEnv("PORT", "8080"))
if err != nil {
return Config{}, fmt.Errorf("PORT must be a number: %w", err)
}
debug, err := strconv.ParseBool(getEnv("DEBUG", "false"))
if err != nil {
return Config{}, fmt.Errorf("DEBUG must be true or false: %w", err)
}
timeout, err := time.ParseDuration(getEnv("TIMEOUT", "5s"))
if err != nil {
return Config{}, fmt.Errorf("TIMEOUT: %w", err)
}
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
return Config{}, fmt.Errorf("DATABASE_URL is required")
}
return Config{Port: port, DBURL: dbURL, Debug: debug, Timeout: timeout}, nil
}
Then call it at the top of main and stop early on any problem.
cfg, err := Load()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", cfg)
$ DATABASE_URL=postgres://localhost/shop PORT=9000 DEBUG=true go run .
{Port:9000 DBURL:postgres://localhost/shop Debug:true Timeout:5s}
$ go run .
2026/08/22 09:00:00 DATABASE_URL is required
Failing fast at startup is much better than crashing later during a customer request. As a result, configuration mistakes show up the moment you deploy.
Setting Go Environment Variables in Tests
func TestLoad(t *testing.T) {
t.Setenv("DATABASE_URL", "postgres://test")
t.Setenv("PORT", "9999")
cfg, err := Load()
if err != nil || cfg.Port != 9999 {
t.Fatalf("got %+v, %v", cfg, err)
}
}
t.Setenv changes a variable only for that test and restores it afterwards. You learned the rest of this pattern in Go unit testing for beginners.
Common Mistakes with Go Environment Variables
| Problem you see | Why it happens | How to fix it |
|---|---|---|
| strconv.Atoi: parsing “abc”: invalid syntax | PORT holds text, not a number. | Validate and return a clear error. |
| App starts with an empty database URL | Getenv hid the missing value. | Check required values in Load. |
| Values in a .env file are ignored | Go does not read .env files on its own. | Export them in the shell or use a loader library. |
| Secrets appear in logs | The whole config was printed. | Mask secret fields before logging. |
Configuration questions appear in many backend interviews. So practise with my Go interview questions and answers.
Official Resources
These pages come straight from the Go team, so they stay accurate and up to date.
Quick Recap
- Go environment variables configure a program without changing code.
LookupEnvtells “missing” apart from “empty”.- Every value is text, so convert it with
strconv. - Load everything into a Config struct once and fail fast.
- Use
t.Setenvto set variables safely in tests.
What’s Next?
Your app now reads its settings from the environment. Next, we will build command line tools that accept options with the flag package.
Next lesson: Go Flag Package: Build Command Line Tools


