env

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2025 License: MIT Imports: 10 Imported by: 0

README

env

A Go module for easily reading environment variables into memory

go get github.com/clickermonkey/env

type TokenConfig struct {
  Token         string        `env:"APP_TOKEN"`
  TokenLifetime time.Duration `env:"APP_TOKEN_LIFETIME" env-default:"2h"`
  TokenMax      uint64        `env:"APP_TOKEN_MAX" env-default:"32"`
}

tokenConfig, err := env.Get[TokenConfig]()
Features
  • Parses via reflection & struct tags
  • Parses all basic data types (primitives, structs, arrays, slices, embedded/anonymous structs)
  • Handles embedded structs and struct fields
  • Caches parsed object (use env.Get[T]())
  • Supports custom unmarshalling & parsing functions
    • env.Unmarshaller
    • encoding.TextUnmarshaler
    • env.RegisterParser[T](fn env.Parser)
  • Supports multiple environment variables per field
  • Supports default values
  • Supports custom delimiters for arrays & slices
  • Supports post-validation logic
    • env.Validator
  • Supports nested variable names
    type Connection struct {
        User string `env:"USER"`
        Pass string `env:"PASS"`
        Host string `env:"HOST"`
        Port uint16 `env:"PORT"`
    }
    type Config struct {
        // all variables in field are prefixed with this, so DB_USER_HOST
        UserDatabase Connection `env:"DB_USER_"`
        MainDatabase Connection `env:"DB_MAIN_"`
    }
    
  • Supports unnesting variable names env:"^DB_USER"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// The struct tag which can store the environment variable name(s)
	// Skip can be used to skip a field. When multiple properties are defined,
	// they are examined one at a time until they find a specified value.
	TagEnv = "env"

	// The struct tag which defines a default value.
	TagEnvDefault = "env-default"

	// The struct tag which defines a custom delimiter for a slice/array value.
	TagEnvDelim = "env-delim"

	// The struct tag which defines a custom required option.
	TagEnvRequired = "env-required"

	// The delimiter for multiple environment variable names in the TagEnv struct tag.
	EnvDelimiter = ","

	// The default delimiter for slice/array values.
	DefaultDelimiter = ","

	// The value in the TagEnv struct tag that causes a field to be skipped.
	Skip = "-"

	// The prefix which determines that an environment value is absolute and not relative
	AbsoluteName = "^"

	// A required value (marked required or a non-pointer) is missing from the environment.
	ErrRequired = errors.New("required")

	// A value is missing from input. It may be okay if it's not required.
	ErrMissing = errors.New("missing")
)

Functions

func Get

func Get[T any]() (T, error)

Gets the cached or loads the environment variables for the given type.

func Load

func Load[T any]() (T, error)

Loads the type from environment variables.

func Must added in v0.2.0

func Must[T any]() T

Gets the cached or loads the environment variables for the given type. If an error occurs a panic will be thrown.

func MustLoad added in v0.2.0

func MustLoad[T any]() T

Loads the type from environment variables. If an error occurs a panic will be thrown.

func Parse

func Parse(value any) error

Loads the value (expected to be pointer) from environment variables.

func RegisterParser

func RegisterParser[T any](parser Parser)

Registers a custom parser for the given type.

Types

type Parser

type Parser func(state UnmarshalState) (any, error)

A custom parser for a given type.

type UnmarshalState

type UnmarshalState struct {
	Field     *reflect.StructField
	Variables []string
	// contains filtered or unexported fields
}

The state of unmarshalling a value from the environment.

func (UnmarshalState) Default

func (us UnmarshalState) Default(otherwise string) (string, bool)

Returns the default value specified on the struct tag if any exists.

func (UnmarshalState) Delim

func (us UnmarshalState) Delim() (*regexp.Regexp, error)

Returns a regular expression to split array/split values based on the env.TagEnvDelim struct tag and env.DefaultDelimiter.

func (UnmarshalState) Envs

func (us UnmarshalState) Envs(defaultValue string) []string

Returns the partial environment variable names specified in the TagEnv struct tag.

func (*UnmarshalState) Read

func (us *UnmarshalState) Read() (value string, exists bool)

Reads the environment value defined by the variables in this state. Returns the whether the value or a default exists at all.

func (UnmarshalState) Required

func (us UnmarshalState) Required(appearsRequired bool) (bool, error)

Returns whether this value is required based on whether the type appears required and what the TagEnvRequired struct tag says.

func (UnmarshalState) Split

func (us UnmarshalState) Split(s string, times int) ([]string, error)

Returns a split set of values based on the input string, max number of times, and the delimiter expression specified on the struct tag.

func (UnmarshalState) String

func (us UnmarshalState) String() string

Returns the environment variable names for this state, EnvDelimiter delimited.

func (UnmarshalState) Tag

func (us UnmarshalState) Tag(key string, missing string) (string, bool)

Returns the struct tag value for the given key, defaulting to a specific value if it's missing - and returns whether the tag exists.

type Unmarshaller

type Unmarshaller interface {
	UnmarshalEnv(state UnmarshalState) error
}

An unmarshaller of an environment value given the current unmarshalling state.

type Validator

type Validator interface {
	ValidateEnv(state UnmarshalState) error
}

A validator that's ran after successful parsing. This cannot be used in conjuction with env.Unmarshaller or encoding.TextUnmarshaler.

Jump to

Keyboard shortcuts

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