Load Environment Variables Into Config

Read configuration from environment variables with typed parsing and defaults, validating required fields at startup rather than at first use.

GoConfig Management

Code

gosnippet
36 lines
package config

import (
	"fmt"
	"os"
	"strconv"
)

type Config struct {
	Port        int
	DatabaseURL string
	Debug       bool
}

func Load() (Config, error) {
	databaseURL := os.Getenv("DATABASE_URL")
	if databaseURL == "" {
		return Config{}, fmt.Errorf("DATABASE_URL is required")
	}
	port, err := strconv.Atoi(getEnv("PORT", "8080"))
	if err != nil {
		return Config{}, fmt.Errorf("PORT must be a number: %w", err)
	}
	return Config{
		Port:        port,
		DatabaseURL: databaseURL,
		Debug:       getEnv("DEBUG", "false") == "true",
	}, nil
}

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

What the code does

Load Environment Variables Into Config comes down to the functions Load and getEnv.

Error handling is inline: 1 place test err != nil and branch immediately.

Behavior branches on DATABASE_URL read from the process environment at load time.

Points of care

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • Failure is a return value (error), which keeps control flow explicit at every call site.

Using it

Entry signature: func Load() (Config, error)

The surface worth importing is Load; the helpers around it are private to the snippet.

Key statements worth quoting

return Config{}, fmt.Errorf("PORT must be a number: %w", err)
return Config{}, fmt.Errorf("DATABASE_URL is required")
func getEnv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}
	return fallback
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As returned `error` values — 1 site in the snippet check `err` before using other results.
Are there dependencies to manage?
No. There are no dependencies to declare or install. Every import resolves inside the standard library — `fmt`, `os`, `strconv`. The file defines `Load`, `getEnv` at load time.