Clone
1
env
Haelnorr edited this page 2026-01-21 19:20:52 +11:00

env v1.0.0

Environment variable utilities for Go applications with type safety and default values.

Installation

go get git.haelnorr.com/h/golib/env

Key Concepts and Features

The env package provides type-safe functions for reading environment variables with automatic fallback to default values. All functions handle missing environment variables gracefully by returning the provided default value.

Supported Types

  • String: Basic string values
  • Integers: int, int8, int16, int32, int64
  • Unsigned Integers: uint, uint8, uint16, uint32, uint64
  • Boolean: Flexible boolean parsing with multiple truthy/falsy values
  • Duration: time.Duration values in nanoseconds

Quick Start

package main

import (
    "fmt"
    "time"
    "git.haelnorr.com/h/golib/env"
)

func main() {
    // String values
    host := env.String("HOST", "localhost")
    
    // Integer values (all sizes supported)
    port := env.Int("PORT", 8080)
    timeout := env.Int64("TIMEOUT_SECONDS", 30)
    
    // Unsigned integer values
    maxConnections := env.UInt("MAX_CONNECTIONS", 100)
    
    // Boolean values (supports many formats)
    debug := env.Bool("DEBUG", false)
    
    // Duration values
    requestTimeout := env.Duration("REQUEST_TIMEOUT", 30*time.Second)
    
    fmt.Printf("Server: %s:%d\n", host, port)
    fmt.Printf("Debug: %v\n", debug)
    fmt.Printf("Timeout: %v\n", requestTimeout)
}

Configuration

Environment Variables

All functions follow the pattern: FunctionName("ENV_VAR_NAME", defaultValue)

String Values

// ENV HOST: Server hostname (default: localhost)
host := env.String("HOST", "localhost")

// ENV DATABASE_URL: Database connection string (required)
dbURL := env.String("DATABASE_URL", "")

Integer Values

// ENV PORT: Server port (default: 8080)
port := env.Int("PORT", 8080)

// ENV MAX_CONNECTIONS: Maximum database connections (default: 10)
maxConn := env.Int16("MAX_CONNECTIONS", 10)

Boolean Values

// ENV DEBUG: Enable debug mode (default: false)
debug := env.Bool("DEBUG", false)

// ENV PRODUCTION: Production mode flag (default: false)
prod := env.Bool("PRODUCTION", false)

Duration Values

// ENV TIMEOUT: Request timeout in seconds (default: 30)
timeout := env.Duration("TIMEOUT", 30*time.Second)

Boolean Parsing

The boolean parser supports many common truthy and falsy values:

Truthy values: true, t, yes, y, on, 1, enable, enabled, active, affirmative Falsy values: false, f, no, n, off, 0, disable, disabled, inactive, negative

All values are case-insensitive and whitespace is trimmed.

Detailed Usage

String Functions

// Basic string with default
apiKey := env.String("API_KEY", "default-key")

// Empty string as default
optional := env.String("OPTIONAL", "")

Integer Functions

All integer types are supported with consistent behavior:

// Different integer sizes
port := env.Int("PORT", 8080)
smallNum := env.Int8("SMALL_NUM", 42)
mediumNum := env.Int16("MEDIUM_NUM", 1000)
largeNum := env.Int32("LARGE_NUM", 100000)
veryLarge := env.Int64("VERY_LARGE", 1000000000)

Unsigned Integer Functions

// Unsigned integers (reject negative values)
maxUsers := env.UInt("MAX_USERS", 1000)
byteValue := env.UInt8("BYTE_VALUE", 255)
shortValue := env.UInt16("SHORT_VALUE", 65535)
normalValue := env.UInt32("NORMAL_VALUE", 4294967295)
bigValue := env.UInt64("BIG_VALUE", 18446744073709551615)

Boolean Functions

// Boolean with various input formats
enabled := env.Bool("ENABLED", false)
verbose := env.Bool("VERBOSE", true)
maintenance := env.Bool("MAINTENANCE", false)

Duration Functions

// Duration in nanoseconds (from integer env var)
timeout := env.Duration("TIMEOUT", 30*time.Second)
heartbeat := env.Duration("HEARTBEAT", 5*time.Second)

Integration

The env package integrates well with other golib packages:

With HWS (Web Server)

import "git.haelnorr.com/h/golib/env"
import "git.haelnorr.com/h/golib/hws"

func main() {
    port := env.Int("PORT", 8080)
    debug := env.Bool("DEBUG", false)
    
    server := hws.NewServer()
    server.SetPort(port)
    server.SetDebug(debug)
    server.Start()
}

With Database Packages

import "git.haelnorr.com/h/golib/env"

func getDBConfig() (host string, port int, timeout time.Duration) {
    host = env.String("DB_HOST", "localhost")
    port = env.Int("DB_PORT", 5432)
    timeout = env.Duration("DB_TIMEOUT", 30*time.Second)
    return
}

Best Practices

  1. Use meaningful defaults: Provide sensible defaults that work in development
  2. Document required variables: Use comments to indicate which variables are required
  3. Prefer specific types: Use the most appropriate integer size for your use case
  4. Handle validation: For complex validation, parse the env var then validate separately
  5. Group related config: Consider using a struct to group related configuration
type ServerConfig struct {
    Host     string
    Port     int
    Debug    bool
    Timeout  time.Duration
}

func LoadServerConfig() *ServerConfig {
    return &ServerConfig{
        Host:    env.String("HOST", "localhost"),
        Port:    env.Int("PORT", 8080),
        Debug:   env.Bool("DEBUG", false),
        Timeout: env.Duration("TIMEOUT", 30*time.Second),
    }
}

Troubleshooting

Common Issues

  1. Parsing errors: All functions return the default value on parsing errors
  2. Type mismatches: Ensure environment variables contain valid values for the target type
  3. Missing variables: Always provide a sensible default value

Debug Tips

// Debug environment variable loading
func debugEnvVars() {
    fmt.Printf("HOST: %s\n", env.String("HOST", "not-set"))
    fmt.Printf("PORT: %d\n", env.Int("PORT", 0))
    fmt.Printf("DEBUG: %v\n", env.Bool("DEBUG", false))
}

See Also

  • HWS - Web server framework that uses env for configuration
  • EZConf - Configuration management system
  • HWSAuth - Authentication package with env-based configuration