aboutsummaryrefslogtreecommitdiffstats

Envelope

Go Reference Version Badge

Envelope is a Go library that makes it easy to populate Go structs from environment variables.

Installation

go get git.eugenetriguba.com/envelope

Quick Start

package main

import (
    "fmt"
    "log"
    "time"

    "git.eugenetriguba.com/envelope"
)

type Config struct {
    Host        string        `env:"HOST"`
    Port        int           `env:"PORT"`
    Debug       bool          `env:"DEBUG"`
    Timeout     time.Duration `env:"TIMEOUT"`
    Database    DatabaseConfig `env:"DB"`
}

type DatabaseConfig struct {
    URL      string `env:"URL"`
    Username string `env:"USERNAME"`
    Password string `env:"PASSWORD"`
}

func main() {
    var config Config
    if err := envelope.LoadFromEnv(&config); err != nil {
        log.Fatalf("Failed to load configuration: %v", err)
    }
    
    fmt.Printf("Configuration: %+v\n", config)
}

Run it with:

export HOST=localhost
export PORT=8080
export DEBUG=true
export TIMEOUT=5s
export DB_URL=postgres://localhost:5432/mydb
export DB_USERNAME=admin
export DB_PASSWORD=secret
go run main.go

Output: Configuration: {Host:localhost Port:8080 Debug:true Timeout:5s Database:{URL:postgres://localhost:5432/mydb Username:admin Password:secret}}

Tutorial

Basic Usage

Envelope uses struct tags to map environment variables to struct fields. The tag name is env.

type ServerConfig struct {
    Host    string `env:"HOST"`
    Port    int    `env:"PORT"`
}

When LoadFromEnv is used on ServerConfig, it will look for environment variables named HOST and PORT and attempt to parse them into the appropriate types.

Supported Types

Envelope supports these types out of the box:

  • String: string
  • Boolean: bool
  • Integer: int, int8, int16, int32, int64
  • Unsigned integer: uint, uint8, uint16, uint32, uint64
  • Floating point: float32, float64
  • Time: time.Time (RFC3339 format)
  • Duration: time.Duration (e.g., “5s”, “1h30m”)
  • IP address: net.IP
  • IP network: net.IPNet (CIDR notation)
  • URL: url.URL
  • String slices: []string (comma-separated)
  • Integer slices: []int (comma-separated)

Nested Structs

Envelope supports nested structs with automatic prefixing of environment variables:

type DatabaseConfig struct {
    URL      string `env:"URL"`
    Username string `env:"USERNAME"`
    Password string `env:"PASSWORD"`
}

type AppConfig struct {
    Database DatabaseConfig `env:"DB"`
    LogLevel string         `env:"LOG_LEVEL"`
}

// LoadFromEnv will look for:
// - DB_URL
// - DB_USERNAME
// - DB_PASSWORD
// - LOG_LEVEL

If you don’t want prefixing for a nested struct, omit the env tag on that field:

type AppConfig struct {
    Database DatabaseConfig // No env tag
    LogLevel string         `env:"LOG_LEVEL"`
}

// LoadFromEnv will look for:
// - URL
// - USERNAME
// - PASSWORD
// - LOG_LEVEL

Custom Type Parsers

You can register custom parsers for your own types:

type CustomType struct {
    Value string
}

envelope.RegisterTypeParser(reflect.TypeOf(CustomType{}), envelope.TypeParserFunc(
    func(value string) (any, error) {
        return CustomType{Value: value}, nil
    },
))

// Now envelope can parse environment variables into CustomType fields

Furthermore, you can override the default supported type parsers by registering your own instead.

envelope.RegisterTypeParser(reflect.TypeOf(time.Time{}), envelope.TypeParserFunc(
    func(value string) (any, error) {
        return time.Parse("01-02-2006", value)
    },
))

// Now time.Time fields will be parsed using MM-DD-YYYY format
// instead of the default RFC3339 format

Error Handling

Envelope may return the following errors from LoadFromEnv:

  • NotPointerToStructError: When the input is not a pointer to a struct
  • UnsupportedTypeError: When a field has a type that’s not supported
  • ParseError: When a value couldn’t be parsed into the target type

Errors can be checked using Go’s standard errors.As():

err := envelope.LoadFromEnv(&config)
var parseErr *envelope.ParseError
if errors.As(err, &parseErr) {
    fmt.Printf("Failed to parse %s from environment variable %s into %v\n",
        parseErr.Value, parseErr.EnvName, parseErr.TargetType)
}

Reference Documentation

For the full API documentation, see the Go reference.