env

package
v1.1.19 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package env provides functionality for unmarshaling environment variables into Go structs.

By default, all exported fields in a struct are mapped to environment variables. The variable name is derived by converting the field's name to uppercase SNAKE_CASE (e.g., a field named APIKey maps to API_KEY). This behavior can be customized or disabled on a per-field basis using struct tags.

Usage

Define a struct to hold your configuration. Only exported fields will be considered. The code snippet below showcases various field types and struct tag options:

type Config struct {
	Host     string        `env:",required"`
	Port     int           `env:",default:8080"`
	Timeout  time.Duration `env:",unit:s"`
	Debug    bool
	Proxy    ProxyConfig   `env:",prefix:'HTTP_PROXY_'"`
	Roles    []string      `env:",split:';'"`
	Internal int           `env:"-"`
	internal int
}

var cfg Config
if err := env.Unmarshal(&cfg); err != nil {
	log.Fatalf("failed to unmarshal config: %v", err)
}
// Use the configuration to bootstrap your application...

Options

The behavior of the unmarshaler is controlled by the env struct field tag. The tag is a comma-separated string of options.

The first value is the name of the environment variable. If it is omitted, the field's name is used as the base for the variable name.

DatabaseURL string `env:"MY_DATABASE_URL"`

The subsequent parts of the tag are options, which can be in a key:value format or be boolean flags.

Option "default"

Sets a default value to be used if the environment variable is not set.

Port int `env:",default:8080"`

Option "required"

Marks the variable as required. Unmarshal will return an error if the variable is not set and no default is provided.

APIKey string `env:",required"`

Option "prefix"

For nested struct fields, this overrides the default prefix. By default, the prefix is the field's name in SNAKE_CASE followed by an underscore. It can be set to an empty string to omit the prefix entirely.

DBConfig `env:",prefix:DB_"`

Option "inline"

When applied to an anonymous struct field, it flattens the struct, effectively treating its fields as if they belonged to the parent struct.

Nested `env:",inline"`

Option "split"

For slice types, this specifies the delimiter to split the environment variable string. The default separator is a comma.

Hosts []string `env:",split:';'"`

Option "format"

Provides a format specifier for special types. For time.Time it can be a Go-compliant layout string (e.g., "2006-01-02") or one of the predefined constants "unix", "dateTime", "date", and "time". Defaults to the RFC 3339 format. For []byte, it can be "hex", "base32", or "base64" to alter the encoding format.

StartDate time.Time `env:",format:date"`

Option "unit"

Specifies the unit for time.Time or time.Duration when parsing from an integer. For time.Duration: "ns", "us" (or "μs"), "ms", "s", "m", "h". For time.Time (with format:unix): "s", "ms", "us" (or "μs").

CacheTTL time.Duration `env:",unit:m,default:5"`

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Expand

func Expand(s string, opts ...Option) (string, error)

Expand substitutes environment variables in a string.

It replaces references to environment variables in the formats ${KEY} or $KEY with their corresponding values. A literal dollar sign can be escaped with $$. If a referenced variable is not found in the environment, the function returns an error. Its behavior can be adjusted through functional options.

func Unmarshal

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

Unmarshal populates the fields of a struct with values from environment variables. The given value v must be a non-nil pointer to a struct.

By default, Unmarshal processes all exported fields. A field's environment variable name is derived from its name, converted to uppercase SNAKE_CASE. To ignore a field, tag it with `env:"-"`. Unexported fields are always excluded. If a variable is not set, the field remains unchanged unless a default value is specified in the struct tag, or it is marked as required.

Types

type Lookup

type Lookup func(key string) (string, bool)

Lookup is a function that retrieves the value of an environment variable. It follows the signature of os.LookupEnv, returning the value and a boolean indicating whether the variable was present. This type allows for custom lookup mechanisms, such as reading from sources other than the actual environment, which is especially useful for testing.

type Option

type Option func(*config)

Option is a function that configures the behavior of the Unmarshal and Expand functions. It follows the functional options pattern.

func WithLookup

func WithLookup(lookup Lookup) Option

WithLookup returns an Option that sets a custom lookup function for retrieving environment variable values. If not customized, os.LookupEnv will be used by default. This is useful for testing or if you need to load environment variables from alternative sources.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix returns an Option that adds a common prefix to all environment variable keys looked up during unmarshaling. For example, WithPrefix("APP_") would cause a field with the env tag "PORT" to look for the "APP_PORT" variable.

type Unmarshaler

type Unmarshaler interface {
	// UnmarshalEnv unmarshals the string value of an environment variable.
	// The value is the raw string from the environment or a default value.
	// It returns an error if the value cannot be parsed.
	UnmarshalEnv(value string) error
}

Unmarshaler is an interface that can be implemented by types to provide their own custom logic for parsing an environment variable string.

Jump to

Keyboard shortcuts

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