Nov 23, 20266 min read

Environment Variables and Config in Go Services

How to read environment variables in Go without the empty-string bugs of os.Getenv, load typed config once at startup and fail fast with every error, use struct-tag libraries, keep .env files local, keep secrets out of the environment, and give each environment its own values in an Encore service.

Illustration for Environment Variables and Config in Go Services

Every Go service reads some configuration from the environment, and the first version is usually os.Getenv sprinkled through the code. It works until a typo in DATABASE_URL turns into a connection to localhost in production, or MAX_WORKERS=ten silently becomes zero, since strconv.Atoi errors were ignored three files away from main.

This guide covers typed config loaded once, failing fast, .env files and where secrets should live instead.

What is the difference between os.Getenv and os.LookupEnv?

os.Getenv returns the value or an empty string, so it cannot tell "unset" from "set to empty". os.LookupEnv returns the value and a boolean:

// config/lookup.go package config import "os" func get(name, fallback string) string { if v, ok := os.LookupEnv(name); ok { return v } return fallback }

The distinction matters for flags such as FEATURE_X="", which someone set on purpose to turn a default off, and for required values, where an unset variable should stop the service rather than run with an empty string.

How do you load typed config at startup?

Read every variable once, in one function, into a struct with typed fields, and collect all problems before returning. errors.Join reports every bad value in one message, so a deploy that is missing three variables fails once with three lines instead of three deploys in a row:

// config/config.go package config import ( "errors" "fmt" "net/url" "os" "strconv" "time" ) type Config struct { Port int PublicBaseURL *url.URL Workers int RequestTimeout time.Duration EnableDigests bool } func Load() (*Config, error) { var errs []error c := &Config{} c.Port = intVar("PORT", 8080, &errs) c.Workers = intVar("WORKERS", 4, &errs) c.RequestTimeout = durationVar("REQUEST_TIMEOUT", 10*time.Second, &errs) c.EnableDigests = get("ENABLE_DIGESTS", "false") == "true" if raw, ok := os.LookupEnv("PUBLIC_BASE_URL"); !ok || raw == "" { errs = append(errs, errors.New("PUBLIC_BASE_URL is required")) } else if u, err := url.Parse(raw); err != nil || u.Scheme != "https" { errs = append(errs, fmt.Errorf("PUBLIC_BASE_URL must be an https URL, got %q", raw)) } else { c.PublicBaseURL = u } if c.Workers < 1 || c.Workers > 64 { errs = append(errs, fmt.Errorf("WORKERS must be between 1 and 64, got %d", c.Workers)) } if err := errors.Join(errs...); err != nil { return nil, err } return c, nil } func intVar(name string, fallback int, errs *[]error) int { raw, ok := os.LookupEnv(name) if !ok { return fallback } n, err := strconv.Atoi(raw) if err != nil { *errs = append(*errs, fmt.Errorf("%s must be an integer, got %q", name, raw)) } return n } func durationVar(name string, fallback time.Duration, errs *[]error) time.Duration { raw, ok := os.LookupEnv(name) if !ok { return fallback } d, err := time.ParseDuration(raw) if err != nil { *errs = append(*errs, fmt.Errorf("%s must be a duration like 10s, got %q", name, raw)) } return d }

main calls config.Load() before opening any connection, logs the joined error and exits non-zero, so a bad deploy fails its health check instead of serving traffic with a half-valid config. Pass the *Config into the code that needs it rather than reading the environment again, which also makes tests simple: build a Config literal instead of calling t.Setenv.

Should you use a config library?

Struct-tag libraries remove the helper functions. caarlos0/env parses tags such as env:"PORT" envDefault:"8080" and env:"PUBLIC_BASE_URL,required" into typed fields, including durations, slices and URLs, and reports every missing required field together. kelseyhightower/envconfig is the older option with a similar shape. Either is fine, and the rules above still apply: load once, validate ranges yourself, fail before serving.

Where do .env files fit?

A .env file is a local convenience. godotenv loads one into the process environment, and it should only run in development, behind a check such as if os.Getenv("APP_ENV") == "local". Add .env to .gitignore and .dockerignore, commit a .env.example with placeholder values, and let the deploy platform set the values in every other environment.

Why should secrets stay out of environment variables?

Environment variables are convenient for secrets and leaky in practice. They show up in docker inspect, in plain-text ECS task definitions and in /proc/PID/environ, they are inherited by every child process, and crash reporters and debug endpoints often dump the whole environment. The twelve-factor guide argues for config in the environment, and secrets deserve an exception: read them from a secret manager at startup and keep the environment for settings that would be harmless if printed. The environment variables vs Secrets Manager guide covers the AWS side.

How does an Encore service handle config and secrets?

Encore

Encore is a backend framework with built-in infrastructure, and it splits the two concerns this guide keeps coming back to. Non-sensitive settings are typed configuration loaded with config.Load from CUE files in the service, where each environment can override a value based on its name or type. Sensitive values are secrets declared as a struct, set per environment with the CLI and never stored in the repository.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create digests --example=hello-world$ cd digests && mkdir notify

The config type is a plain struct, and Encore generates a CUE schema from it:

// notify/notify.go package notify import ( "context" "encore.dev/config" ) type Config struct { PublicBaseURL config.String Workers config.Int EnableDigests config.Bool } var cfg = config.Load[*Config]() var secrets struct { MailAPIKey string } type Settings struct { PublicBaseURL string `json:"public_base_url"` Workers int `json:"workers"` EnableDigests bool `json:"enable_digests"` HasMailKey bool `json:"has_mail_key"` } //encore:api private method=GET path=/notify/settings func GetSettings(ctx context.Context) (*Settings, error) { return &Settings{ PublicBaseURL: cfg.PublicBaseURL(), Workers: cfg.Workers(), EnableDigests: cfg.EnableDigests(), HasMailKey: secrets.MailAPIKey != "", }, nil }

The values live in a CUE file next to the code, with defaults and per-environment overrides that are checked when the app builds:

// notify/config.cue PublicBaseURL: string | *"https://app.acme.dev" Workers: int & >=1 & <=64 | *4 EnableDigests: bool | *false if #Meta.Environment.Type == "development" && #Meta.Environment.Cloud != "local" { PublicBaseURL: "https://staging.acme.dev" EnableDigests: true } if #Meta.Environment.Cloud == "local" { PublicBaseURL: "http://localhost:4000" Workers: 1 }

Set the mail key per environment and start the app:

~/digests
$ encore secret set --type prod MailAPIKey$ encore secret set --type dev,local MailAPIKey$ encore run

A value outside the >=1 & <=64 range fails the build, not the first request, which is the fail-fast behavior of the hand-written loader without the helper functions. The mail key is not stored in the repository, and its value never appears in a task definition you maintain, so a coding agent working in the service cannot read or leak it while it changes config defaults or adds a setting in the same CUE file and tests it with encore run.

Best fit: Go services with settings that differ between local, staging and production and secrets that should never sit in the repository or a task definition.

Go config checklist

  • Use os.LookupEnv when unset and empty mean different things.
  • Load all config once at startup into a typed struct, and pass it down.
  • Validate ranges and formats, and report every error together with errors.Join.
  • Load .env files only locally, and never commit or bake them into images.
  • Keep secrets in a secret manager, not in plain environment variables.

Frequently asked questions

How do I read an environment variable in Go?

Use os.Getenv("NAME") for a string, which returns an empty string when the variable is unset, or os.LookupEnv("NAME"), which also returns a boolean saying whether it was set. Use LookupEnv whenever an empty value and a missing value mean different things.

How do I set a default value for an environment variable in Go?

Go has no built-in default, so write a small helper that calls os.LookupEnv and returns the fallback when the variable is not set, or use a library such as caarlos0/env with an envDefault struct tag. Parse the result into the right type once, at startup.

Should I load .env files in production Go services?

No. Load a .env file with godotenv only in local development, and let the platform set environment variables in deployed environments. A .env file in a container image or repository is a common way secrets leak.

Are environment variables safe for secrets?

No, not on their own. Environment variables are visible to anyone who can inspect the process, container or task definition, are inherited by child processes and often end up in crash reports and logs. Read secrets from a secret manager at startup instead, and keep the environment for non-sensitive settings.

How does an Encore service get configuration and secrets?

Configuration can still come from environment variables parsed at startup, and secret values are declared in code and stored outside the repository, so they are not checked into git. encore run provides local values, and each deployed environment gets its own.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders