envconfig

repository·master·Indexed 26 days ago

https://github.com/kelseyhightower/envconfig

A Go library for populating configuration structs directly from environment variables. It supports basic scalars, slices, maps, time.Duration, and custom types via the Decoder and Setter interfaces. Features include struct tag customization for defaults and requirements, automatic CamelCase to snake_case conversion, and utilities for generating environment variable usage documentation.

Tokens
2.3K
Snippets
4
Records
14
Agent score
88%

What's inside envconfig

  1. Configure environment variables using struct tags

    master

    You can use struct tags to customize how fields are mapped to environment variables:

    • envconfig:"name": Specifies an alternate environment variable name (after the prefix).
    • default:"value": Sets a default value if the environment variable is not present.
    • required:"true": Returns an error during processing if the environment variable is missing (note: an empty string is considered present).
    • ignored:"true": The field will not be processed even if a matching environment variable exists.
    • split_words:"true": Enables automatic CamelCase to snake_case conversion. For example, AutoSplitVar becomes MYAPP_AUTO_SPLIT_VAR instead of MYAPP_AUTOSPLITVAR.
    type Specification struct {
        ManualOverride1 string `envconfig:"manual_override_1"` 
        DefaultVar      string `default:"foobar"` 
        RequiredVar     string `required:"true"` 
        IgnoredVar      string `ignored:"true"` 
        AutoSplitVar    string `split_words:"true"` 
        RequiredAndAutoSplitVar    string `required:"true" split_words:"true"` 
    }
  2. Implement custom decoders for environment variables

    master

    To support custom types, implement the envconfig.Decoder interface by adding a Decode(value string) error method to your type. This allows you to control exactly how a string from an environment variable is parsed into your specific data structure.

    Additionally, envconfig will use a Set(string) error method if your type implements the flag.Value interface.

    type IPDecoder net.IP
    
    func (ipd *IPDecoder) Decode(value string) error {
        *ipd = IPDecoder(net.ParseIP(value))
        return nil
    }
    
    type DNSConfig struct {
        Address IPDecoder `envconfig:"DNS_SERVER"` 
    }
  3. Load environment variables into a struct with envconfig.Process

    master

    Use envconfig.Process(prefix string, dest *struct) to populate a struct with values from environment variables. The prefix string is prepended to the environment variable names (e.g., if the prefix is myapp, a struct field Port will look for MYAPP_PORT).

    Supported types include basic scalars (string, int, bool, float), slices, maps, time.Duration, and types implementing encoding.TextUnmarshaler or encoding.BinaryUnmarshaler.

    package main
    
    import (
        "fmt"
        "log"
        "time"
    
        "github.com/kelseyhightower/envconfig"
    )
    
    type Specification struct {
        Debug       bool
        Port        int
        User        string
        Users       []string
        Rate        float32
        Timeout     time.Duration
        ColorCodes  map[string]int
    }
    
    func main() {
        var s Specification
        err := envconfig.Process("myapp", &s)
        if err != nil {
            log.Fatal(err.Error())
        }
        // ... use s
    }
  4. Configure struct fields using envconfig tags

    master

    Use struct tags to control how environment variables are mapped to fields:

    • envconfig:"NAME": Overrides the default environment variable name (the field name uppercased).
    • default:"VALUE": Sets a default value if the environment variable is not present.
    • required:"true": Returns an error if the environment variable is missing and no default is provided.
    • ignored:"true": Tells envconfig to skip this field.
    • split_words:"true": Attempts to split camelCase field names into underscore-separated environment variables (e.g., MyField becomes MY_FIELD).
  5. Reference: Supported struct field types

    master

    envconfig supports the following types for environment variable mapping:

    • string
    • int8, int16, int32, int64
    • bool
    • float32, float64
    • Slices of any supported type
    • Maps (where keys and values are any supported type)
    • Types implementing encoding.TextUnmarshaler
    • Types implementing encoding.BinaryUnmarshaler
    • time.Duration
  6. Implement custom deserialization with Setter or Decoder

    master

    You can implement custom logic for parsing environment variables into specific types by implementing one of the following interfaces on your type:

    1. Decoder: Takes precedence. Requires a Decode(value string) error method.
    2. Setter: Used if Decoder is not implemented. Requires a Set(value string) error method (this is also compatible with flag.Value).

    If neither is implemented, envconfig will attempt to use encoding.TextUnmarshaler or encoding.BinaryUnmarshaler if the type supports them.

  7. Validate environment variables with CheckDisallowed

    master
    CheckDisallowed(prefix string, spec interface{}) error ensures that no environment variables exist with the specified prefix that are not explicitly mapped to the provided struct. This is useful for catching typos in configuration or preventing unexpected environment variables from being ignored.
  8. Display environment variable usage via Usage()

    master
    Use Usage(prefix string, spec interface{}) to write environment variable usage information directly to os.Stdout. It uses a default header and a tabular format to display the environment variable keys, types, default values, requirement status, and descriptions (extracted from desc struct tags).
  9. Display environment variable usage with custom formatting via Usagef()

    master

    Use Usagef(prefix string, spec interface{}, out io.Writer, format string) to write usage information to a specific io.Writer using a custom template string.

    Available template functions:

    • usage_key: Returns the environment variable key.
    • usage_description: Returns the value of the desc struct tag.
    • usage_type: Returns a human-readable description of the Go type.
    • usage_default: Returns the value of the default struct tag.
    • usage_required: Returns true if the required struct tag is set to a truthy value, otherwise returns an empty string.
  10. Panic on parsing error with MustProcess

    master
    MustProcess(prefix string, spec interface{}) is a convenience wrapper around Process. It behaves identically but will panic if any environment variable cannot be successfully converted to the type required by the struct field. Use this when configuration errors should be treated as fatal startup failures.
  11. Display environment variable usage with a custom template via Usaget()

    master
    Use Usaget(prefix string, spec interface{}, out io.Writer, tmpl *template.Template) to write usage information to an io.Writer using a pre-parsed *template.Template object. This is useful if you want to reuse a parsed template for multiple calls.
  12. Populate a struct from environment variables with Process

    master

    Use Process(prefix string, spec interface{}) error to populate a struct pointer with values from environment variables. The prefix is prepended to the environment variable names (in uppercase). The spec must be a pointer to a struct.

    If an error occurs during parsing, it returns a *ParseError which provides details about the failed key, field, and type.