configloader

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(value any, opts ...Option) error

Load populates a struct's fields with values from environment variables. It takes a pointer to a struct and optional configuration options.

Each struct field's name is converted to SCREAMING_SNAKE_CASE to determine the environment variable name. For example:

  • Field "ServerPort" looks for "SERVER_PORT"
  • Field "DatabaseURL" looks for "DATABASE_URL"
  • Nested field "Database.Password" looks for "DATABASE_PASSWORD"

Supported field types out of the box:

  • Basic types: string, bool, int*, uint*, float*
  • time.Duration, time.Time (RFC3339 format)
  • net.IP, *net.IPNet (CIDR)
  • *url.URL, *regexp.Regexp
  • json.RawMessage
  • []byte (base64 encoded)
  • Slices of any supported type (comma-separated values)

Features:

  • Custom type support via WithTypeHandler
  • Default values via struct tags: `default:"value"`
  • Custom env names via struct tags: `env:"CUSTOM_NAME"`
  • Optional prefix for all env vars: WithPrefix("APP")
  • Nested struct support
  • Pointer fields are automatically initialized

Example usage:

type Config struct {
    Port        int           `default:"8080"`
    Host        string        `env:"SERVICE_HOST"`
    Timeout     time.Duration
    Database struct {
        URL      string
        Password string
    }
}

var cfg Config
err := configloader.Load(&cfg,
    WithPrefix("APP"),
    WithNameTag("env"),
    WithDefaultTag("default"),
)

The above will look for these environment variables:

  • APP_PORT (default: "8080")
  • SERVICE_HOST (custom name via tag)
  • APP_TIMEOUT
  • APP_DATABASE_URL
  • APP_DATABASE_PASSWORD

Returns an error if:

  • The value is not a pointer to a struct
  • Required environment variables are missing
  • Type conversion fails for any field
  • Any field has an unsupported type

Types

type ConfigLoadError

type ConfigLoadError struct {
	Value  reflect.Type
	Errors []error
}

ConfigLoadError represents the errors that occurred during config loading.

func (*ConfigLoadError) Add

func (e *ConfigLoadError) Add(err error)

func (*ConfigLoadError) Error

func (e *ConfigLoadError) Error() string

func (*ConfigLoadError) Unwrap

func (e *ConfigLoadError) Unwrap() []error

type Field

type Field struct {
	Value reflect.Value
	Path  []reflect.StructField
}

func (*Field) Last

func (f *Field) Last() reflect.StructField

func (*Field) Names

func (f *Field) Names() (names []string)

func (*Field) String

func (f *Field) String() string

type FieldError

type FieldError struct {
	Field
	Err error
}

FieldError represents an error that occurred while processing a specific field.

func (FieldError) Error

func (e FieldError) Error() string

func (FieldError) Unwrap

func (e FieldError) Unwrap() error

type Loader

type Loader struct {
	// contains filtered or unexported fields
}

func (*Loader) Load

func (l *Loader) Load(val any) error

type MissingEnvError

type MissingEnvError struct {
	Key string
}

MissingEnvError represents an error when a required environment variable is not found.

func (MissingEnvError) Error

func (e MissingEnvError) Error() string

type Option

type Option func(*Loader)

func WithDefaultTag

func WithDefaultTag(tag string) Option

WithDefaultTag sets the struct tag used for specifying default values. If an environment variable is not found, the value of this tag will be used instead.

Example:

type Config struct {
    Port int `default:"8080"`  // Will use 8080 if PORT is not set
}
configloader.Load(&cfg, WithDefaultTag("default"))

func WithEnv

func WithEnv(env func(string) (string, bool)) Option

WithEnv sets a custom function for looking up environment variables. This is primarily useful for testing or when environment variables need to be sourced from somewhere other than os.LookupEnv.

The function should return the value and a boolean indicating whether the variable was found, similar to os.LookupEnv.

func WithEnvTag

func WithEnvTag(tag string) Option

WithEnvTag sets the struct tag used to completely override the environment variable name for a field. When a field has this tag, its value is used as-is for the environment variable name, bypassing all other name construction rules including prefixes and path building.

Example with WithEnvTag("env"):

type Config struct {
    Database struct {
        // Despite nesting, looks directly for "DB_HOST"
        Host string `env:"DB_HOST"`
    }
}
configloader.Load(&cfg)

Example showing prefix is ignored with env tag:

type Config struct {
    Database struct {
        // Still only looks for "DB_HOST", prefix is not applied
        Host string `env:"DB_HOST"`
    }
}
configloader.Load(&cfg, WithPrefix("APP"))

func WithNameTag

func WithNameTag(tag string) Option

WithNameTag sets the struct tag used to override a field's name in the environment variable path. The tag value replaces just the field's name segment while still following the normal path construction rules (prefix + path + name).

Example with WithNameTag("name"):

type Config struct {
    Database struct {
        Host string `name:"HOSTNAME"` // Looks for DATABASE_HOSTNAME
    }
}
configloader.Load(&cfg)

Example with both prefix and name tag:

type Config struct {
    Database struct {
        Host string `name:"HOSTNAME"` // Looks for APP_DATABASE_HOSTNAME
    }
}
configloader.Load(&cfg, WithPrefix("APP"))

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix sets a prefix that will be prepended to all environment variable names. The prefix and field name will be joined with an underscore.

Example:

type Config struct {
    Port int  // Will look for "APP_PORT" environment variable
}
configloader.Load(&cfg, WithPrefix("APP"))

func WithTypeHandler

func WithTypeHandler[T any](f func(string) (T, error)) Option

WithTypeHandler registers a custom type conversion function for a specific type T. The function should convert a string environment value to type T, returning an error if the conversion fails.

Example:

configloader.Load(&cfg, WithTypeHandler(func(s string) (time.Duration, error) {
    return time.ParseDuration(s)
}))

type UnsupportedTypeError

type UnsupportedTypeError struct {
	Type reflect.Type
}

UnsupportedTypeError represents an error when trying to process a field with an unsupported type.

func (UnsupportedTypeError) Error

func (e UnsupportedTypeError) Error() string

Jump to

Keyboard shortcuts

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