env

package
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 11 Imported by: 1

README

Environment Module

The environment module provides utilities for working with environment variables, including normalized access, type-safe retrieval, and .env file loading.

Features

  • Normalized Environment Access: Consistent naming conventions for environment variables
  • Type-Safe Retrieval: Safe conversion to common types (bool, int, float)
  • .env File Support: Automatic loading of .env files with godotenv
  • Environment Expansion: ${NAME}, ${NAME:default} and ${NAME:-default} substitution
  • Flexible Lookup: Multiple fallback mechanisms for variable resolution

Installation

go get github.com/pubgo/funk/v2/env

Quick Start

Basic Environment Access
import "github.com/pubgo/funk/v2/env"

// Get environment variable with fallback
host := env.GetOr("SERVER_HOST", "localhost")

// Get environment variable or panic if not set
port := env.MustGet("SERVER_PORT")

// Get with multiple fallback names
dbHost := env.Get("DB_HOST", "DATABASE_HOST", "MYSQL_HOST")
Type-Safe Access
import "github.com/pubgo/funk/v2/env"

// Boolean values (supports: true, 1, on, yes)
debug := env.GetBool("DEBUG", "ENABLE_DEBUG")

// Integer values
port := env.GetInt("PORT", "SERVER_PORT")

// Float values
timeout := env.GetFloat("TIMEOUT", "REQUEST_TIMEOUT")
.env File Loading
import "github.com/pubgo/funk/v2/env"

// Load .env file
env.LoadFiles(".env", "config/.env.local")

// Access variables from loaded files
apiKey := env.Get("API_KEY")

Core Concepts

Environment Variable Normalization

The module normalizes environment variable names to ensure consistency:

// These are all equivalent after normalization:
// server-host => SERVER_HOST
// server.host => SERVER_HOST
// server/host => SERVER_HOST
// SERVER-HOST => SERVER_HOST

host := env.Get("server-host")  // Matches SERVER_HOST
Multiple Name Lookup

Functions support multiple names for flexible variable resolution:

// Looks for DB_HOST, then DATABASE_HOST, then MYSQL_HOST
dbHost := env.Get("DB_HOST", "DATABASE_HOST", "MYSQL_HOST")
Safe Type Conversion

Type-safe getters provide graceful handling of conversion errors:

// GetInt returns -1 on conversion error
port := env.GetInt("PORT")
if port == -1 {
    port = 8080  // default
}

// GetBool handles various truthy values
debug := env.GetBool("DEBUG")  // true for "true", "1", "on", "yes"

Advanced Usage

Environment Variable Expansion
import "github.com/pubgo/funk/v2/env"

// Expand environment variables in strings
template := "http://${HOST}:${PORT:-8080}"
expanded := env.Expand(template).UnwrapOr(template)

Supported syntax:

Syntax Behavior
${NAME} / $NAME Environment value, empty when unset
${NAME:default} / ${NAME:-default} default when unset or empty; everything after the first : is the default, surrounding quotes are stripped
$$ Escapes a literal $

Keys resolve in order: the raw name, the normalized key (env.Key), then the normalized uppercase key — so keys containing digits resolve regardless of the case-sensitive renaming done by Set/Reload (${sha256sum}, ${SHA256SUM} and ${SHA256_SUM} all find a variable declared as SHA256SUM).

Migrating from a8m/envsubst: only the forms in the table above are supported. bash-specific operators were dropped: ${VAR-word} (no colon), ${VAR:=word}, ${VAR:+word}, ${VAR:?err}, #VAR length, substring offsets (${VAR:1:3} — the part after the first : is now a plain default), nested defaults (${VAR:-$OTHER}), and // replacements. Do not use ${VAR-word}: the whole VAR-word is parsed as a name and may resolve to a different existing variable (VAR_WORD); write ${VAR:-word} instead.

Process Environment Rewriting

env.Reload() (also triggered by env.LoadFiles) renormalizes the entire process environment in place: every key is renamed through normalization (a-b -> A_B) and keys starting with _ or = are removed. Child processes spawned afterwards inherit the rewritten environment — including variables the process did not create. Call it only when that global effect is intended, typically once at startup after loading .env files.

Environment Manipulation
import "github.com/pubgo/funk/v2/env"

// Set environment variables
env.Set("CUSTOM_VAR", "value").Log()

// Delete environment variables
env.Delete("UNUSED_VAR").Log()

// Check if variable exists
if val, exists := env.Lookup("OPTIONAL_VAR"); exists {
    fmt.Printf("Optional var: %s\n", val)
}
Environment Mapping
import "github.com/pubgo/funk/v2/env"

// Get all environment variables as a map
allVars := env.Map()

// Process all variables
for key, value := range allVars {
    fmt.Printf("%s=%s\n", key, value)
}

API Reference

Core Functions
Function Description
Get(names ...string) Get environment variable with fallback names
MustGet(names ...string) Get environment variable or panic if not set
GetOr(name, defaultVal string) Get with explicit default value
Set(key, value string) Set environment variable
MustSet(key, value string) Set environment variable or panic on error
Delete(key string) Delete environment variable
MustDelete(key string) Delete environment variable or panic on error
Type-Safe Getters
Function Description
GetBool(names ...string) Get boolean value
GetInt(names ...string) Get integer value
GetFloat(names ...string) Get float value
Lookup(key string) Lookup variable existence
File Operations
Function Description
LoadFiles(files ...string) Load .env files, missing files are skipped
MustLoadFiles(files ...string) Load .env files, panics on failure
Expand(value string) Expand environment variables in string
Utility Functions
Function Description
Map() Get all environment variables as map
Key(key string) Normalize environment variable key
Normalize(key string) Normalize key with validity check

Best Practices

  1. Use Descriptive Names: Choose clear, descriptive environment variable names
  2. Provide Sensible Defaults: Always consider reasonable default values
  3. Validate Early: Validate environment variables at startup
  4. Document Variables: Document all environment variables your application uses
  5. Group Related Variables: Use consistent naming prefixes for related variables
  6. Avoid Sensitive Logging: Be careful not to log sensitive environment variables

Integration Patterns

With Configuration
import (
    "github.com/pubgo/funk/v2/env"
    "github.com/pubgo/funk/v2/config"
)

type Config struct {
    Server struct {
        Host string `yaml:"host"`
        Port int    `yaml:"port"`
    } `yaml:"server"`
}

// Environment variables are automatically substituted in config files
cfg := config.Load[Config]()

// Override with environment variables if needed
if host := env.Get("SERVER_HOST"); host != "" {
    cfg.T.Server.Host = host
}
With Feature Flags
import (
    "github.com/pubgo/funk/v2/env"
    "github.com/pubgo/funk/v2/features"
)

// Create feature flag with environment variable default
var debugMode = features.Bool("debug", env.GetBool("DEBUG"), "Enable debug mode")

// Create feature flag with environment variable lookup
var logLevel = features.String("log_level", env.GetOr("LOG_LEVEL", "info"), "Logging level")
With Logging
import (
    "github.com/pubgo/funk/v2/env"
    "github.com/pubgo/funk/v2/log"
)

logger := log.GetLogger("env")

// Log environment variable loading
env.LoadFiles(".env").Log(logger.RecordErr())

// Log specific variable access
host := env.Get("SERVER_HOST")
logger.Info().Str("host", host).Msg("Server host configured")

Documentation

Index

Constants

View Source
const Name = "env"

Variables

This section is empty.

Functions

func Delete

func Delete(key string) result.Error

Delete unsets every stored spelling of key (raw, normalized and normalized uppercase), so variables saved under a renamed key are removed as well.

func Expand

func Expand(value string) result.Result[string]

Expand substitutes environment variable references in value.

Supported syntax:

  • ${NAME} value of NAME, empty when unset
  • ${NAME:default} default when NAME is unset or empty
  • ${NAME:-default} same as ${NAME:default}
  • ${NAME:"default"} default with surrounding quotes stripped
  • $NAME bare form, name starts with a letter or '_'

Names are resolved against the raw environment first, then against the normalized key (see keyHandler), so variables renamed by Set/Reload still resolve: ${T2HOST} finds T2_HOST stored via env.Set("T2HOST", ...).

func Get

func Get(names ...string) string

func GetBool

func GetBool(names ...string) bool

func GetBoolOr added in v2.1.0

func GetBoolOr(name string, defaultVal bool) bool

GetBoolOr returns the parsed bool value of name, defaultVal when the variable is unset, empty or not a valid bool.

func GetFloat

func GetFloat(names ...string) float64

func GetFloatOr added in v2.1.0

func GetFloatOr(name string, defaultVal float64) float64

GetFloatOr returns the parsed float value of name, defaultVal when the variable is unset, empty or not a valid float.

func GetInt

func GetInt(names ...string) int

func GetIntOr added in v2.1.0

func GetIntOr(name string, defaultVal int) int

GetIntOr returns the parsed int value of name, defaultVal when the variable is unset, empty or not a valid int.

func GetOr

func GetOr(name, defaultVal string) string

func GetWith

func GetWith(val *string, names ...string)

func Key

func Key(key string) string

func LoadFiles

func LoadFiles(files ...string) (r result.Error)

func Lookup

func Lookup(key string) (string, bool)

func Map

func Map() map[string]string

func MustDelete

func MustDelete(key string)

func MustGet

func MustGet(names ...string) string

func MustLoadFiles added in v2.1.0

func MustLoadFiles(files ...string)

MustLoadFiles behaves like LoadFiles and panics on failure. Missing files are still skipped silently, matching LoadFiles.

func MustSet

func MustSet(key, value string)

func Normalize

func Normalize(key string) (string, bool)

Normalize a-b=>a_b, a.b=>a_b, a/b=>a_b

func Reload

func Reload()

Reload re-normalizes the whole process environment in place.

WARNING: this mutates variables the process did not create. Every key is renamed through Normalize (a-b -> A_B) and keys starting with '_' or '=' are removed, so child processes spawned afterwards inherit the rewritten environment. Only call it when that global effect is intended, e.g. right after loading .env files at startup.

func Set

func Set(key, value string) result.Error

Types

This section is empty.

Jump to

Keyboard shortcuts

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