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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithTagName selects the struct tag mapstructure uses for field names. Default: "mapstructure". Set "env" to use `env:"FIELD_NAME"` tags.
func WithTrim ¶
WithTrim toggles automatic TrimSpace on string values. Default: true. Use WithTrim(false) when whitespace is semantically meaningful.
func WithWeaklyTyped ¶
WithWeaklyTyped toggles mapstructure's WeaklyTypedInput. Default: true. When true, "1" decodes into int, "true" into bool, etc. Disable for strict string-only decoding.