caarlos0/env

repository·main·Indexed 27 days ago

https://github.com/caarlos0/env

A zero-dependencies Go library used to parse environment variables into structs using struct tags. It supports built-in types, time.Duration, url.URL, and custom parsers via FuncMap. The library provides pointer-based Parse and generic-based ParseAs functions, along with advanced configuration options for prefixes, default values, and custom environment maps.

Tokens
2.6K
Snippets
7
Records
22
Agent score
92%

What's inside caarlos0/env

  1. Parse environment variables into structs

    main

    You can parse environment variables into a struct using either the pointer-based Parse function or the generic-based ParseAs function.

    Note: Unexported fields in your struct will be ignored by the parser.

    type config struct {
      Home string `env:"HOME"`
    }
    
    // parse using a pointer
    var cfg config
    err := env.Parse(&cfg)
    
    // parse using generics
    cfg, err := env.ParseAs[config]()
  2. Configure parser Options

    main

    The Options struct allows fine-grained control over the parsing process:

    FieldDescription
    EnvironmentA map[string]string containing the environment variables to use. Defaults to os.Environ().
    TagNameThe tag name used to identify environment variable keys (default: "env").
    PrefixTagNameThe tag name used to identify prefixes for nested structs (default: "envPrefix").
    DefaultValueTagNameThe tag name used to identify default values (default: "envDefault").
    RequiredIfNoDefIf true, all fields without an envDefault tag are treated as required.
    OnSetAn OnSetFn hook executed whenever a value is successfully set.
    PrefixA string prefix applied to all environment variable keys.
    UseFieldNameByDefaultIf true, uses the struct field name (converted to uppercase/underscore) if the env tag is missing.
    SetDefaultsForZeroValuesOnlyIf true, envDefault is ignored if the struct field already has a non-zero value.
    FuncMapA map[reflect.Type]ParserFunc for defining custom parsing logic for specific types.
  3. Reference: Supported types

    main

    The library supports all built-in types, plus several common types and complex structures. Supported types include:

    • bool
    • float32, float64
    • int8, int16, int32, int64, int
    • uint8, uint16, uint32, uint64, uint
    • string
    • time.Duration
    • time.Location
    • encoding.TextUnmarshaler
    • url.URL

    Pointers, slices, slices of pointers, and maps of these types are also supported. You can also add custom parsers for your own types.

  4. Reference: Struct tags

    main

    Use these tags on your struct fields to control how environment variables are mapped and processed:

    - `env`: sets the environment variable name and optionally takes the tag options described below
    - `envDefault`: sets the default value for the field
    - `envPrefix`: can be used in a field that is a complex type to set a prefix to all environment variables used in it
    - `envSeparator`: sets the character to be used to separate items in slices and maps (default: `,`)
    - `envKeyValSeparator`: sets the character to be used to separate keys and their values in maps (default: `:`)
  5. Reference: `env` tag options

    main

    These options can be appended to the env tag (e.g., `env:"VAR_NAME,required"`):

    - `,expand`: expands environment variables, e.g. `FOO_${BAR}`
    - `,file`: instructs that the content of the variable is a path to a file that should be read
    - `,init`: initialize nil pointers
    - `,notEmpty`: make the field errors if the environment variable is empty
    - `,required`: make the field errors if the environment variable is not set
    - `,unset`: unset the environment variable after use
  6. Reference: Parse Options

    main

    When using ParseWithOptions or ParseAsWithOptions, you can provide a configuration object with the following options:

    - `Environment`: keys and values to be used instead of `os.Environ()`
    - `TagName`: specifies another tag name to use rather than the default `env`
    - `PrefixTagName`: specifies another prefix tag name to use rather than the default `envPrefix`
    - `DefaultValueTagName`: specifies another default tag name to use rather than the default `envDefault`
    - `RequiredIfNoDef`: set all `env` fields as required if they do not declare `envDefault`
    - `OnSet`: allows to hook into the `env` parsing and do something when a value is set
    - `Prefix`: prefix to be used in all environment variables
    - `UseFieldNameByDefault`: defines whether or not `env` should use the field name by default if the `env` key is missing
    - `FuncMap`: custom parse functions for custom types
  7. Reference: Parsing functions

    main

    The following functions are available for parsing the environment into types:

    - `Parse`: parse the current environment into a type
    - `ParseAs`: parse the current environment into a type using generics
    - `ParseWithOptions`: parse the current environment into a type with custom options
    - `ParseAsWithOptions`: parse the current environment into a type with custom options and using generics
    - `Must`: can be used to wrap `Parse.*` calls to panic on error
    - `GetFieldParams`: get the `env` parsed options for a type
    - `GetFieldParamsWithOptions`: get the `env` parsed options for a type with custom options
  8. Convert environment slice to map

    main
    Use env.ToMap to convert a slice of environment strings (like the output of os.Environ()) into a map[string]string. This is useful for providing a controlled environment to Options.Environment.
  9. Parse environment variables into a struct

    main

    Use env.Parse to populate an existing struct instance with values from environment variables based on env tags. Alternatively, use env.ParseAs[T] to create and return a new instance of type T populated with environment values.

    type config struct {
    	Home string `env:"HOME"`
    }
    
    // parse into existing struct
    var cfg config
    err := env.Parse(&cfg)
    
    // or parse using generics
    cfg, err := env.ParseAs[config]()
  10. Configure the parser with Options

    main
    Use env.ParseWithOptions or env.ParseAsWithOptions to customize the parsing behavior. You can provide a custom environment map, change the tag names used for configuration, set a global prefix, or provide custom type parsers via FuncMap.
  11. Use custom ParserFunc for specific types

    main
    You can extend the library's parsing capabilities by providing a FuncMap in the Options struct. A ParserFunc must match the signature func(v string) (interface{}, error).