02-environment

command
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2025 License: MIT Imports: 3 Imported by: 0

README

Example 02: Environment Variables

Loading configuration from environment variables with prefix handling.

What This Shows

  • Using FromEnv to load environment variables
  • Prefix stripping (MYAPP_ prefix is removed during matching)
  • Layer precedence (environment overrides defaults)
  • How non-prefixed variables are ignored

Running

go run main.go

Key Points

  1. FromEnv - Creates a layer from environment variables
  2. Prefix Stripping - MYAPP_SERVER_PORT matches server.port
  3. Precedence - Later layers (environment) override earlier ones (defaults)
  4. Selective Loading - Only variables with the prefix are included

Environment Variable Matching

The library automatically matches environment variables to configuration keys:

  • MYAPP_SERVER_PORTserver.port
  • MYAPP_DATABASE_HOSTdatabase.host
  • MYAPP_FEATURE_BETAfeature.beta

Output Example

=== Layer Contents ===

Layer: defaults (prefix: "")
  server.port = 8080
  server.host = localhost
  database.host = localhost
  ...

Layer: environment (prefix: "MYAPP_")
  MYAPP_SERVER_PORT = 9000
  MYAPP_DATABASE_HOST = db.production.com
  ...

=== Resolved Configuration ===
server.port          = 9000                (from environment)
server.host          = localhost           (from defaults)
database.host        = db.production.com   (from environment)
...

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL