envconfig

package module
v3.0.0-...-2cbd73f Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2025 License: MIT Imports: 12 Imported by: 0

README

envconfig

Package envconfig will populate your config struct based on sources such as environment variables, files, etc.

Installation

go get github.com/h-dav/envconfig/v3

Features

Options
Option Description
WithFilepath("config/file.env") Use file to populate config struct.
WithActiveProfile("dev_env") Provide the profile to select a specific config file.
Struct Tags
  • env: Used to determine the key of the value to use when populating config fields.
  • required: true or false
  • default: Default value if environment variable is not set.
  • prefix: Used for nested structures.
  • envjson: Used for deserialising JSON into config.
Other
  • Text Replacement: ${EXAMPLE} can be used to insert other discovered values.

Merging Values

[!IMPORTANT] When merging values, envconfig uses the following precedence:

  1. Flags
  2. Environment Variables
  3. Config File (provided via WithFilepath())

Examples

Basic
func main() {
    type Config struct {
        Development bool `env:"DEVELOPMENT" default:"true"`
    }

    var cfg Config

    if err := envconfig.Set(&cfg); err != nil {
        panic(err)
    }
}
Config File
func main() {
    type Config struct {
        Service string `env:"SERVICE"`
    }

    var cfg Config

    if err := envconfig.Set(&cfg, WithFilepath("internal/config/config.env")); err != nil {
        panic(err)
    }
}
Profile
func main() {
    type Config struct {
        Service string `env:"SERVICE"`
    }

    var cfg Config

    if err := envconfig.Set(
        &cfg,
        WithActiveProfile(os.Getenv("ACTIVE_PROFILE")),
        WithFilepath("internal/config/"), // Will use file `internal/config/development.env`.
    ); err != nil {
        panic(err)
    }
}
Nested Structs
func main() {
    type Config struct {
        Service struct {
            Name string `env:"NAME"`
            Version string `env:"VERSION"`
        } `prefix:"SERVICE_"`
    }

    var cfg Config

    if err := envconfig.Set(&cfg); err != nil {
        panic(err)
    }
}

Documentation

Overview

Package envconfig provides functionality to easily load config into your struct.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrSyntax = errors.New("invalid syntax")

ErrSyntax indicates that a line is invalid syntax.

Functions

func Set

func Set(config any, opts ...option) error

Set will parse multiple sources for config values, and use these values to populate the passed in config struct.

Example
type Config struct {
	Value string `env:"VALUE"`
}

os.Setenv("VALUE", "value")

var cfg Config

envconfig.Set(&cfg)

fmt.Println(cfg.Value)
Output:

value

func WithActiveProfile

func WithActiveProfile(activeProfile string) option

func WithDecoders

func WithDecoders(decoders map[reflect.Type]DecoderFunc) option

func WithFilepath

func WithFilepath(filepath string) option

WithFilepath option will cause the file provided to be used to set variables in the environment.

func WithPrefix

func WithPrefix(prefix string) option

WithPrefix option will add the prefix to before every set and retrieval from env.

Types

type DecoderFunc

type DecoderFunc func(key, value string) (reflect.Value, error)

type EnvironmentVariableSource

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

func (EnvironmentVariableSource) Load

func (s EnvironmentVariableSource) Load() (map[string]string, error)

processEnvironmentVariables populates the config struct using all environment variables.

type FieldConversionError

type FieldConversionError struct {
	FieldName  string
	TargetType string
	Err        error
}

FieldConversionError occurs when a field on the config struct fails to be set.

func (*FieldConversionError) Error

func (e *FieldConversionError) Error() string

Error satisfies the error interface for FieldConversionError.

func (*FieldConversionError) Unwrap

func (e *FieldConversionError) Unwrap() error

Unwrap allows FieldConversionError to be used with errors.Is and errors.As.

type FileReadError

type FileReadError struct {
	Filepath string
	Err      error
}

FileReadError occurs when an error occurs when scanning the .env file.

func (*FileReadError) Error

func (e *FileReadError) Error() string

Error satisfies the error interface for FileReadError.

func (*FileReadError) Unwrap

func (e *FileReadError) Unwrap() error

Unwrap allows FileReadError to be used with errors.Is and errors.As.

type FileSource

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

func (FileSource) Load

func (s FileSource) Load() (map[string]string, error)

type FileTypeValidationError

type FileTypeValidationError struct {
	Filepath string
}

FileTypeValidationError occurs when the .env config file fails to open.

func (*FileTypeValidationError) Error

func (e *FileTypeValidationError) Error() string

Error satisfies the error interface for FileTypeValidationError.

type FlagSource

type FlagSource struct{}

func (FlagSource) Load

func (s FlagSource) Load() (map[string]string, error)

type IncompatibleOptionsError

type IncompatibleOptionsError struct {
	FirstOption  string
	SecondOption string
	Reason       string
}

IncompatibleOptionsError occurs when two options are incompatible with each other, or the usage is invalid.

func (*IncompatibleOptionsError) Error

func (e *IncompatibleOptionsError) Error() string

Error satisfies the error interface for FileReadError.

type InvalidConfigTypeError

type InvalidConfigTypeError struct {
	ProvidedType any
}

InvalidConfigTypeError occurs when config is not a pointer to a struct.

func (*InvalidConfigTypeError) Error

func (e *InvalidConfigTypeError) Error() string

Error satisfies the error interface for InvalidConfigTypeError.

type InvalidOptionConversionError

type InvalidOptionConversionError struct {
	FieldName string
	Option    string
	Err       error
}

InvalidOptionConversionError occurs when an option is invalid for a field.

func (*InvalidOptionConversionError) Error

Error satisfies the error interface for InvalidOptionConversionError.

func (*InvalidOptionConversionError) Unwrap

func (e *InvalidOptionConversionError) Unwrap() error

Unwrap allows InvalidOptionConversionError to be used with errors.Is and errors.As.

type OpenFileError

type OpenFileError struct {
	Err error
}

OpenFileError occurs when the .env config file fails to open.

func (*OpenFileError) Error

func (e *OpenFileError) Error() string

Error satisfies the error interface for OpenFileError.

func (*OpenFileError) Unwrap

func (e *OpenFileError) Unwrap() error

Unwrap allows OpenFileError to be used with errors.Is and errors.As.

type ParseError

type ParseError struct {
	Line string
	Err  error
}

ParseError occurs when a line from the .env config file has been parsed incorrectly.

func (*ParseError) Error

func (e *ParseError) Error() string

Error statisfies the error interface for ParseError.

type PrefixOptionError

type PrefixOptionError struct {
	FieldName any
}

PrefixOptionError occurs when the prefix tag is invalid or not set on a nested struct.

func (*PrefixOptionError) Error

func (e *PrefixOptionError) Error() string

Error satisfies the error interface for PrefixOptionError.

type ReplacementError

type ReplacementError struct {
	VariableName string
}

ReplacementError occurs when the environment variable being used for replacement is not set.

func (*ReplacementError) Error

func (e *ReplacementError) Error() string

Error satisfies the error interface for ReplacementError.

type RequiredFieldError

type RequiredFieldError struct {
	FieldName string
}

RequiredFieldError occurs when a required field is not set and in the environment variables.

func (*RequiredFieldError) Error

func (e *RequiredFieldError) Error() string

Error satisfies the error interface for RequiredFieldError.

type SetEnvironmentVariableError

type SetEnvironmentVariableError struct {
	Err error
}

SetEnvironmentVariableError occurs when the value is failed to be set in the environment.

func (*SetEnvironmentVariableError) Error

Error satisfies the error interface for SetEnvironmentVariableError.

func (*SetEnvironmentVariableError) Unwrap

func (e *SetEnvironmentVariableError) Unwrap() error

Unwrap allows SetEnvironmentVariableError to be used with errors.Is and errors.As.

type Setter

type Setter interface {
	Set(value string) error
}

type UnsupportedFieldTypeError

type UnsupportedFieldTypeError struct {
	FieldType any
}

UnsupportedFieldTypeError occurs when the a field type on the config struct is not compatible.

func (*UnsupportedFieldTypeError) Error

func (e *UnsupportedFieldTypeError) Error() string

Error satisfies the error interface for UnsupportedFieldTypeError.

Jump to

Keyboard shortcuts

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