env

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 5 Imported by: 0

README

go-env

Go Reference

Tiny, zero-ceremony library for decoding process environment variables into Go structs.

  • Uses _ as a path separator: SERVICE_HTTP_PORT → Service.HTTP.Port.
  • Weakly-typed by default ("1" → int, "true" → bool).
  • Optional prefix filter with automatic stripping.
  • Pluggable decode hooks via mitchellh/mapstructure.

Install

go get github.com/eslider/go-env

Quick start

package main

import (
	"fmt"

	"github.com/eslider/go-env"
)

type Config struct {
	Service struct {
		HTTP struct {
			Port int
		}
		Key string
	}
}

func main() {
	var cfg Config
	if err := env.Unmarshal(&cfg); err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", cfg)
}

With a prefix:

// Only looks at APP_* variables; strips the APP_ prefix before decoding.
_ = env.UnmarshalPrefix(&cfg, "APP_")

API

Function Purpose
Unmarshal(dst, opts...) Decode all env vars into dst.
UnmarshalPrefix(dst, prefix, opts...) Same, but only vars starting with prefix.
AsMap() / AsMapPrefix(prefix) Return the nested map[string]any used by the decoder (debugging, custom decoders).
Options
Option Default Purpose
WithTrim(bool) true TrimSpace every string value.
WithWeaklyTyped(bool) true mapstructure's weakly-typed coercion.
WithTagName(string) "mapstructure" Struct tag name for field overrides.
WithDecodeHook(h) — Append a mapstructure.DecodeHookFunc to the chain.

Semantics

  • Path collisions: first write wins. If both FOO=1 and FOO=2 exist in the environ, only FOO=1 is kept. This matches the original ai-fabric/pkg/env behaviour.
  • Case-insensitive keys: all path components are lower-cased; struct fields are matched via mapstructure which is also case-insensitive.
  • _-only delimiter: there's no escape — if a variable legitimately contains _ inside a "leaf" name, you must restructure your struct to match the nested layout.

Status

Extracted from produktor.io/ai-fabric as part of the eSlider go-* library standard (ASR-0008). Merges the best parts of three previously divergent copies:

  • produktor.io/ai-fabric/pkg/env
  • markets-platform/TP-general-code/pkg/system/env.go
  • the various pkg/system/env.go snapshots inside var/agents/issue-*/

License

MIT © Andriy Oblivantsev

Documentation

Overview

Package env reads process environment variables and decodes them into Go structs using underscore-delimited paths.

A variable named "SERVICE_HTTP_PORT" becomes the path Service.HTTP.Port (case-insensitive, '_' is a path separator). Values are decoded via github.com/mitchellh/mapstructure, so numeric, boolean and slice conversions happen automatically.

var cfg struct {
	Service struct {
		HTTP struct {
			Port int
		}
		Key string
	}
}
if err := env.Unmarshal(&cfg); err != nil { ... }

UnmarshalPrefix ignores variables that don't start with the given prefix and strips it before building the path:

_ = os.Setenv("APP_DB_HOST", "localhost")
_ = env.UnmarshalPrefix(&cfg, "APP_")
// cfg.Db.Host == "localhost"

String values are TrimSpace-trimmed by default; pass WithTrim(false) to opt out.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsMap

func AsMap() map[string]any

AsMap returns a nested map built from all current process environment variables, using '_' as path separator. Keys are lower-cased.

It's primarily useful for debugging or for callers that want to plug their own decoder; normal code should prefer Unmarshal.

func AsMapPrefix

func AsMapPrefix(prefix string) map[string]any

AsMapPrefix is the prefix-scoped variant of AsMap. Variables whose names don't start with prefix are skipped; the prefix itself is stripped before the map is built.

func Unmarshal

func Unmarshal(dst any, opts ...Option) error

Unmarshal decodes all process environment variables into dst. The variable name is split by '_' and the resulting path is matched against dst's fields case-insensitively.

dst must be a pointer to a struct (or a map that mapstructure can populate). See the package documentation for details and examples.

func UnmarshalPrefix

func UnmarshalPrefix(dst any, prefix string, opts ...Option) error

UnmarshalPrefix is like Unmarshal but only considers environment variables that start with prefix. The prefix is stripped from each variable name before the path is built.

An empty prefix is equivalent to Unmarshal.

Types

type Option

type Option func(*options)

Option customises Unmarshal/UnmarshalPrefix behaviour.

func WithDecodeHook

func WithDecodeHook(h mapstructure.DecodeHookFunc) Option

WithDecodeHook appends a user hook to the decoder chain. Hooks run after the built-in trim hook (unless trimming is disabled) and in the order they're added.

func WithTagName

func WithTagName(name string) Option

WithTagName selects the struct tag mapstructure uses for field names. Default: "mapstructure". Set "env" to use `env:"FIELD_NAME"` tags.

func WithTrim

func WithTrim(enable bool) Option

WithTrim toggles automatic TrimSpace on string values. Default: true. Use WithTrim(false) when whitespace is semantically meaningful.

func WithWeaklyTyped

func WithWeaklyTyped(enable bool) Option

WithWeaklyTyped toggles mapstructure's WeaklyTypedInput. Default: true. When true, "1" decodes into int, "true" into bool, etc. Disable for strict string-only decoding.

Jump to

Keyboard shortcuts

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