envcfg

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2025 License: MIT Imports: 11 Imported by: 0

README

envcfg

Parse environment variables into Go structs with minimal boilerplate and first-class support for complex data structures

Go Reference Go Report Card Coverage Test Status Release License

Key Features

✨ Zero Configuration Philosophy
  • Field names just work (snake or camel)
  • Nested structs automatically create prefixes
  • No special tags needed
🔄 Smart Tag Fallbacks
  • When field name doesn't match, tries existing json/yaml/toml etc.. tags
  • Explicit env tags available and take highest precedence, but rarely needed
🎯 Simple Environment Variables
  • One string value per variable
  • No need to encode complex data in environment values
🧩 Complex Types Made Simple
  • Maps: SETTINGS_KEY=value
  • Arrays: PORTS_0=8080
  • Nested structs: REDIS_HOST=localhost
  • Slice of structs: SERVERS_0_HOST=host1
  • Map of structs: DATABASES_PRIMARY_HOST=host1
  • Most features from popular libraries available
🛠️ Fully Configurable
  • No lock-in to specific tag formats, tags are all configurable
  • Default settings are all configurable
  • Parsers/decoders are all configurable

Table of Contents

Installation

go get github.com/sethpollack/envcfg

Quick Start

Set the following environment variables:

# string
export NAME=name
# integer
export PORT=8080
# float
export RATE=1.23
# boolean
export IS_ENABLED=true
# duration
export TIMEOUT=60s
# nested struct
export REDIS_HOST=localhost
export REDIS_PORT=6379
# delimited slice
export TAGS=tag1,tag2,tag3
# indexed slice
export PORTS_0=8080
export PORTS_1=9090
# slice of structs
export SERVERS_0_HOST=localhost1
export SERVERS_0_PORT=8080
export SERVERS_1_HOST=localhost2
export SERVERS_1_PORT=9090
# key-value map
export LABELS=key1:value1,key2:value2
# flat map
export SETTINGS_KEY1=1
export SETTINGS_KEY2=2
# map of structs
export DATABASES_PRIMARY_HOST=localhost1
export DATABASES_PRIMARY_PORT=6379
export DATABASES_SECONDARY_HOST=localhost2
export DATABASES_SECONDARY_PORT=6380

Parse the environment variables into a struct:

package main

import (
	"fmt"
	"time"

	"github.com/sethpollack/envcfg"
)

func main() {
	type ServerConfig struct {
		Host string
		Port int
	}

	type Config struct {
		Name      string
		Port      int
		Rate      float64
		IsEnabled bool
		Timeout   time.Duration

		Redis ServerConfig

		Tags    []string
		Ports   []int
		Servers []ServerConfig

		Labels    map[string]string
		Settings  map[string]int
		Databases map[string]ServerConfig

	}

	cfg := Config{}
	if err := envcfg.Parse(&cfg); err != nil {
		panic(err)
	}

	fmt.Printf(`Config:
  Name: %s
  Port: %d
  Rate: %.2f
  IsEnabled: %t
  Timeout: %s
  Redis:
    Host: %s
    Port: %d
  Tags: %v
  Ports: %v
  Servers: [
    {Host: %s, Port: %d},
    {Host: %s, Port: %d}
  ]
  Labels: %v
  Settings: %v
  Databases: {
    primary: {Host: %s, Port: %d},
    secondary: {Host: %s, Port: %d}
  }
`,
		cfg.Name, cfg.Port, cfg.Rate, cfg.IsEnabled, cfg.Timeout,
		cfg.Redis.Host, cfg.Redis.Port,
		cfg.Tags, cfg.Ports,
		cfg.Servers[0].Host, cfg.Servers[0].Port,
		cfg.Servers[1].Host, cfg.Servers[1].Port,
		cfg.Labels, cfg.Settings,
		cfg.Databases["primary"].Host, cfg.Databases["primary"].Port,
		cfg.Databases["secondary"].Host, cfg.Databases["secondary"].Port,
	)
}

Results:

Config:
  Name: name
  Port: 8080
  Rate: 1.23
  IsEnabled: true
  Timeout: 1m0s
  Redis:
    Host: localhost
    Port: 6379
  Tags: [tag1 tag2 tag3]
  Ports: [8080 9090]
  Servers: [
    {Host: localhost1, Port: 8080},
    {Host: localhost2, Port: 9090}
  ]
  Labels: map[key1:value1 key2:value2]
  Settings: map[key1:1 key2:2]
  Databases: {
    primary: {Host: localhost1, Port: 6379},
    secondary: {Host: localhost2, Port: 6380}
  }

[!TIP] The example above demonstrates the three supported syntaxes for both slices and maps:

  • Slices:
    • delimited TAGS=tag1,tag2,tag3
    • indexed PORTS_0=8080
    • struct SERVERS_0_HOST=localhost
  • Maps:
    • key-value pairs LABELS=key1:value1
    • flat keys SETTINGS_KEY1=1
    • struct DATABASES_PRIMARY_HOST=localhost

Types

  • string
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • bool
  • float32, float64
  • time.Duration
  • structs
  • slices
  • maps

[!NOTE] Type support can be extended using the WithKindParser and WithTypeParser options.

Decoders

  • envcfg.Decoder
  • flag.Value
  • encoding.TextUnmarshaler
  • encoding.BinaryUnmarshaler

[!NOTE] Decoder support can be extended using the WithDecoder option.

Struct Tags

Name Description Default Example Tag Example Option
default Default value when environment variable is not set - default:"8080" env:",default=8080"
required Mark field as required false required:"true" env:",required"
notempty Ensure value is not empty false notempty:"true" env:",notempty"
expand Expand environment variables in value false expand:"true" env:",expand"
file Load value from file false file:"true" env:",file"
delim Delimiter for array values , delim:";" env:",delim=;"
sep Separator for map key-value pairs : sep:"=" env:",sep="
init Initialize nil pointers vars init:"always" env:",init=always"
ignore Ignore field false ignore:"true" env:",ignore" or env:"-"
decodeunset Decode unset environment variables false decodeunset:"true" env:",decodeunset"

[!WARNING] When setting default values for slices, avoid using the comma as it conflicts with tag parsing. Either use a different delimiter or set array values using environment variables:

type Config struct {
    Tags []string `env:"TAGS,default=tag1,tag2"` // This will fail!
}

// Do this instead:
type Config struct {
    Tags []string `env:"TAGS,delim=;,default=tag1;tag2"` // Use a different delimiter
}
Init Options
  • vars - Initialize when values are present with the exception of structs that only have default values. (default)
  • any - Same as vars, but also initialize structs that only have default values.
  • always - Always initialize
  • never - Never initialize

[!TIP] All defaults and tag names can be customized using the With* options. See Configuration Options for more details.

Field Name Mapping

By default, envcfg will search for environment variables using multiple naming patterns until a match is found. Use WithDisableFallback to restrict matching to only the env tag value.

For example:

os.Setenv("DATABASEURL",  "value") // Matches struct field
os.Setenv("DATABASE_URL", "value") // Matches snake-case
os.Setenv("DB_URL",      "value") // Matches json tag
os.Setenv("DATA_SOURCE", "value") // Matches yaml tag
os.Setenv("CUSTOM_URL",  "value") // Matches env tag

type Config struct {
    DatabaseURL string `json:"db_url" yaml:"data_source" env:"custom_url"`
}

[!TIP] All environment variable matching is case insensitive.

Functions

  • Parse - Parse environment variables into a struct pointer
  • MustParse - Same as Parse, but panics on error
  • ParseAs - Parse environment variables into a specific type
  • MustParseAs - Same as ParseAs, but panics on error

[!IMPORTANT] envcfg only parses exported fields.

Configuration Options
Tag Overrides
Option Description Default
WithTagName Tag name for environment variables env
WithDelimiterTag Tag name for delimiter delim
WithSeparatorTag Tag name for separator sep
WithDecodeUnsetTag Tag name for decoding unset environment variables decodeunset
WithDefaultTag Tag name for default values default
WithExpandTag Tag name for expandable variables expand
WithFileTag Tag name for file variables file
WithNotEmptyTag Tag name for not empty variables notempty
WithRequiredTag Tag name for required variables required
WithIgnoreTag Tag name for ignored variables ignore
WithInitTag Tag name for initialization strategy init
Default Overrides
Option Description Default
WithDelimiter Sets the default delimiter for array and map values ,
WithSeparator Sets the default separator for map key-value pairs :
WithDecodeUnset Enables decoding unset environment variables by default false
WithInitAny Sets the initialization strategy to any vars
WithInitNever Sets the initialization strategy to never vars
WithInitAlways Sets the initialization strategy to always vars
WithExpand Enables environment variable expansion by default false
WithNotEmpty Enables validating that values are not empty by default false
WithRequired Enables marking fields as required by default false
WithDisableFallback Enables strict matching using the env tag false
Custom Parser Functions
Option Description
WithTypeParser Registers a custom type parser
WithTypeParsers Registers custom type parsers
WithKindParser Registers a custom kind parser
WithKindParsers Registers custom kind parsers
Custom Decoder Functions
Option Description
WithDecoder Registers a custom decoder function for a specific interface
Loaders
Option Description
WithLoader Registers a loader
Loader Options

Loader options configure how environment variables are loaded and filtered before being matched to struct fields. These options allow you to:

  • Add different sources of configuration (environment variables, files, external services)
  • Filter which environment variables are considered
  • Transform environment variable names before matching
  • Set default values for when environment variables are not found
Option Description
WithSource Adds a source to the loader
WithSources Adds multiple sources to the loader
WithOSEnvSource Adds OS environment variables as a source
WithMapEnvSource Uses the provided map of environment variables as a source
WithDotEnvSource Adds environment variables from a file as a source
WithPrefix Combines WithTrimPrefix and WithHasPrefix
WithSuffix Combines WithTrimSuffix and WithHasSuffix
WithTransform Adds a transform function that modifies environment variable keys
WithTrimPrefix Removes a prefix from environment variable names
WithTrimSuffix Removes a suffix from environment variable names
WithFilter Adds a custom filter to the loader
WithHasPrefix Adds a prefix filter to the loader
WithHasSuffix Adds a suffix filter to the loader
WithHasMatch Adds a pattern filter to the loader
Configuration Sources

envcfg supports multiple configuration sources that can be used individually or combined. Built-in sources have dedicated With* functions, while custom sources and those maintained as separate Go modules (to keep dependencies isolated) can be added using WithSource.

Option Description
WithOSEnvSource Adds OS environment variables as a source
WithMapEnvSource Uses the provided map of environment variables as a source
WithDotEnvSource Adds environment variables from a .env file as a source
WithSource(awssm.New(...)) Adds AWS Secrets Manager as a source
Source Ordering

Sources are processed in the order they are added, with later sources taking precedence over earlier ones. This ordering allows you to:

  • Set default values by adding a source with defaults first
  • Override values by adding sources with higher precedence later
  • Create a hierarchy of configuration (e.g., defaults → shared config → environment-specific config → local overrides)
  envcfg.Parse(&cfg,
    envcfg.WithLoader(
      envcfg.WithMapEnvSource(map[string]string{
          "APP_PORT": "8080",
        "LOG_LEVEL": "info",
      }),
      envcfg.WithDotEnvSource(".env"),
      envcfg.WithSource(awssm.New(
        awssm.WithRegion("us-west-2"),
        awssm.WithSecretID("myapp/config"),
      )),
      envcfg.WithOSEnvSource(),
    ),
)

In this setup:

  1. Default values are loaded first
  2. Then values from the .env file are loaded next
  3. Then values from AWS Secrets Manager
  4. Finally, OS environment variables take precedence over both defaults and .env file

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustParse

func MustParse(cfg any, opts ...Option)

MustParse is like Parse but panics if an error occurs during parsing.

func MustParseAs

func MustParseAs[T any](opts ...Option) T

MustParseAs is like ParseAs but panics if an error occurs during parsing.

func Parse

func Parse(cfg any, opts ...Option) error

Parse processes the provided configuration struct using environment variables and the specified options. It traverses the struct fields and applies the environment configuration according to the defined rules and options.

Example
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/sethpollack/envcfg"
)

func main() {
	os.Setenv("NAME", "name")
	os.Setenv("PORT", "8080")
	os.Setenv("RATE", "1.23")
	os.Setenv("IS_ENABLED", "true")
	os.Setenv("TIMEOUT", "60s")
	os.Setenv("REDIS_HOST", "localhost")
	os.Setenv("REDIS_PORT", "6379")
	os.Setenv("TAGS", "tag1,tag2,tag3")
	os.Setenv("PORTS_0", "8080")
	os.Setenv("PORTS_1", "9090")
	os.Setenv("SERVERS_0_HOST", "localhost1")
	os.Setenv("SERVERS_0_PORT", "8080")
	os.Setenv("SERVERS_1_HOST", "localhost2")
	os.Setenv("SERVERS_1_PORT", "9090")
	os.Setenv("LABELS", "key1:value1,key2:value2")
	os.Setenv("SETTINGS_KEY1", "1")
	os.Setenv("SETTINGS_KEY2", "2")
	os.Setenv("DATABASES_PRIMARY_HOST", "localhost1")
	os.Setenv("DATABASES_PRIMARY_PORT", "6379")
	os.Setenv("DATABASES_SECONDARY_HOST", "localhost2")
	os.Setenv("DATABASES_SECONDARY_PORT", "6380")

	defer os.Clearenv()

	type ServerConfig struct {
		Host string
		Port int
	}

	type Config struct {
		Name      string
		Port      int
		Rate      float64
		IsEnabled bool
		Timeout   time.Duration
		Redis     ServerConfig
		Tags      []string
		Ports     []int
		Servers   []ServerConfig
		Labels    map[string]string
		Settings  map[string]int
		Databases map[string]ServerConfig
	}

	cfg := Config{}
	if err := envcfg.Parse(&cfg); err != nil {
		panic(err)
	}

	fmt.Printf(`Config:
  Name: %s
  Port: %d
  Rate: %.2f
  IsEnabled: %t
  Timeout: %s
  Redis:
    Host: %s
    Port: %d
  Tags: %v
  Ports: %v
  Servers: [
    {Host: %s, Port: %d},
    {Host: %s, Port: %d}
  ]
  Labels: %v
  Settings: %v
  Databases: {
    primary: {Host: %s, Port: %d},
    secondary: {Host: %s, Port: %d}
  }
`,
		cfg.Name, cfg.Port, cfg.Rate, cfg.IsEnabled, cfg.Timeout,
		cfg.Redis.Host, cfg.Redis.Port,
		cfg.Tags, cfg.Ports,
		cfg.Servers[0].Host, cfg.Servers[0].Port,
		cfg.Servers[1].Host, cfg.Servers[1].Port,
		cfg.Labels, cfg.Settings,
		cfg.Databases["primary"].Host, cfg.Databases["primary"].Port,
		cfg.Databases["secondary"].Host, cfg.Databases["secondary"].Port,
	)

}
Output:

Config:
  Name: name
  Port: 8080
  Rate: 1.23
  IsEnabled: true
  Timeout: 1m0s
  Redis:
    Host: localhost
    Port: 6379
  Tags: [tag1 tag2 tag3]
  Ports: [8080 9090]
  Servers: [
    {Host: localhost1, Port: 8080},
    {Host: localhost2, Port: 9090}
  ]
  Labels: map[key1:value1 key2:value2]
  Settings: map[key1:1 key2:2]
  Databases: {
    primary: {Host: localhost1, Port: 6379},
    secondary: {Host: localhost2, Port: 6380}
  }
Example (FieldMatching)
package main

import (
	"fmt"
	"os"

	"github.com/sethpollack/envcfg"
)

func main() {
	os.Setenv("FIELDNAME", "field name")
	os.Setenv("SNAKE_FIELD_NAME", "snake field name")
	os.Setenv("TOML_OVERRIDE", "toml override")
	os.Setenv("ENV_FIELD_NAME", "env field name")

	defer os.Clearenv()

	type Config struct {
		FieldName      string
		SnakeFieldName string
		TomlFieldName  string `toml:"toml_override"`
		EnvFieldName   string `env:"ENV_FIELD_NAME"`
	}

	cfg := Config{}
	if err := envcfg.Parse(&cfg); err != nil {
		panic(err)
	}

	fmt.Printf("%+v\n", cfg)
}
Output:

{FieldName:field name SnakeFieldName:snake field name TomlFieldName:toml override EnvFieldName:env field name}
Example (Options)
package main

import (
	"fmt"
	"os"

	"github.com/sethpollack/envcfg"
)

func main() {
	tmpfile, err := os.CreateTemp("", "test.txt")
	if err != nil {
		panic(err)
	}
	defer os.Remove(tmpfile.Name())

	_, err = tmpfile.WriteString("${FILE_CONTENTS}")
	if err != nil {
		panic(err)
	}

	os.Setenv("EXPAND", "${EXPAND_OTHER}")
	os.Setenv("EXPAND_OTHER", "expand other")
	os.Setenv("FILE_CONTENTS", "file contents")
	os.Setenv("FILE", tmpfile.Name())
	os.Setenv("EXPAND_FILE", tmpfile.Name())
	os.Setenv("IGNORE", "ignore")
	os.Setenv("INIT_VALUES_FIELD", "init values")
	os.Setenv("INIT_NEVER_FIELD", "init never")

	defer os.Clearenv()

	type Nested struct {
		Field string
	}

	type Config struct {
		Default       string  `env:",default=default value"`
		ExpandDefault string  `env:",expand,default=${EXPAND_OTHER}"`
		Expand        string  `env:",expand"`
		File          string  `env:",file"`
		ExpandFile    string  `env:",expand,file"`
		Ignore        string  `env:"-"`
		InitValues    *Nested `env:",init=values"`
		InitAlways    *Nested `env:",init=always"`
		InitNever     *Nested `env:",init=never"`
	}

	cfg := Config{}
	err = envcfg.Parse(&cfg)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Default: %v, ExpandDefault: %v, Expand: %v, File: %v, ExpandFile: %v, Ignore: %v, InitValues: %v, InitAlways: %v, InitNever: %v",
		cfg.Default, cfg.ExpandDefault, cfg.Expand, cfg.File, cfg.ExpandFile, cfg.Ignore, cfg.InitValues, cfg.InitAlways, cfg.InitNever,
	)
}
Output:

Default: default value, ExpandDefault: expand other, Expand: expand other, File: ${FILE_CONTENTS}, ExpandFile: file contents, Ignore: , InitValues: &{init values}, InitAlways: &{}, InitNever: <nil>
Example (Tags)
package main

import (
	"fmt"
	"os"

	"github.com/sethpollack/envcfg"
)

func main() {
	tmpfile, err := os.CreateTemp("", "test.txt")
	if err != nil {
		panic(err)
	}
	defer os.Remove(tmpfile.Name())

	_, err = tmpfile.WriteString("${FILE_CONTENTS}")
	if err != nil {
		panic(err)
	}

	os.Setenv("EXPAND", "${EXPAND_OTHER}")
	os.Setenv("EXPAND_OTHER", "expand other")
	os.Setenv("FILE_CONTENTS", "file contents")
	os.Setenv("FILE", tmpfile.Name())
	os.Setenv("EXPAND_FILE", tmpfile.Name())
	os.Setenv("IGNORE", "ignore")
	os.Setenv("INIT_VALUES_FIELD", "init values")
	os.Setenv("INIT_NEVER_FIELD", "init never")

	defer os.Clearenv()

	type Nested struct {
		Field string
	}

	type Config struct {
		Default       string  `default:"default value"`
		ExpandDefault string  `expand:"true" default:"${EXPAND_OTHER}"`
		Expand        string  `expand:"true"`
		File          string  `file:"true"`
		ExpandFile    string  `expand:"true" file:"true"`
		Ignore        string  `ignore:"true"`
		InitValues    *Nested `init:"values"`
		InitAlways    *Nested `init:"always"`
		InitNever     *Nested `init:"never"`
	}

	cfg := Config{}
	if err := envcfg.Parse(&cfg); err != nil {
		panic(err)
	}

	fmt.Printf("Default: %v, ExpandDefault: %v, Expand: %v, File: %v, ExpandFile: %v, Ignore: %v, InitValues: %v, InitAlways: %v, InitNever: %v",
		cfg.Default, cfg.ExpandDefault, cfg.Expand, cfg.File, cfg.ExpandFile, cfg.Ignore, cfg.InitValues, cfg.InitAlways, cfg.InitNever,
	)
}
Output:

Default: default value, ExpandDefault: expand other, Expand: expand other, File: ${FILE_CONTENTS}, ExpandFile: file contents, Ignore: , InitValues: &{init values}, InitAlways: &{}, InitNever: <nil>
Example (ValidationNotempty)
package main

import (
	"fmt"
	"os"

	"github.com/sethpollack/envcfg"
)

func main() {
	os.Setenv("NOT_EMPTY", "")
	defer os.Clearenv()

	type Config struct {
		NotEmpty string `notempty:"true"`
	}

	cfg := Config{}
	err := envcfg.Parse(&cfg)

	fmt.Printf("%+v\n", err)
}
Output:

environment variable NOT_EMPTY is empty
Example (ValidationRequired)
package main

import (
	"fmt"
	"os"

	"github.com/sethpollack/envcfg"
)

func main() {
	defer os.Clearenv()

	type Config struct {
		Required string `required:"true"`
	}

	cfg := Config{}
	err := envcfg.Parse(&cfg)

	fmt.Printf("%+v\n", err)
}
Output:

required field Required not found

func ParseAs

func ParseAs[T any](opts ...Option) (T, error)

ParseAs is a generic version of Parse that creates and returns a new instance of the specified type T with the environment configuration applied.

Types

type LoaderOption added in v0.2.0

type LoaderOption func(*loader.Loader)

func WithDotEnvSource

func WithDotEnvSource(path string) LoaderOption

WithDotEnvSource adds environment variables from a file as a source. The file should contain environment variables in KEY=VALUE format.

func WithFilter

func WithFilter(filter func(string) bool) LoaderOption

WithFilter registers a custom filter function for environment variables. The filter function is used to determine which environment variables should be used.

func WithHasMatch

func WithHasMatch(pattern regexp.Regexp) LoaderOption

WithHasMatch filters environment variables using a regular expression pattern.

func WithHasPrefix

func WithHasPrefix(prefix string) LoaderOption

WithHasPrefix filters environment variables by prefix but preserves the prefix during matching. For example, with prefix "APP_", the environment variable "APP_PORT=8080" would be matched as "APP_PORT=8080".

func WithHasSuffix

func WithHasSuffix(suffix string) LoaderOption

WithHasSuffix filters environment variables by suffix but preserves the suffix during matching. For example, with suffix "_TEST", the environment variable "PORT_TEST=8080" would be matched as "PORT_TEST=8080".

func WithMapEnvSource

func WithMapEnvSource(envs map[string]string) LoaderOption

WithMapEnvSource uses the provided map of environment variables instead of reading from the OS environment.

func WithOSEnvSource

func WithOSEnvSource() LoaderOption

WithOSEnvSource adds OS environment variables as a source.

func WithPrefix

func WithPrefix(prefix string) LoaderOption

WithPrefix filters environment variables by prefix and strips the prefix before matching. For example, with prefix "APP_", the environment variable "APP_PORT=8080" would be matched as "PORT=8080".

func WithSource

func WithSource(source loader.Source) LoaderOption

WithSource adds a source to the loader.

func WithSources

func WithSources(sources ...loader.Source) LoaderOption

WithSources adds multiple sources to the loader. This is a convenience function for adding multiple sources at once.

func WithSuffix

func WithSuffix(suffix string) LoaderOption

WithSuffix filters environment variables by suffix and strips the suffix during matching. For example, with suffix "_TEST", the environment variable "PORT_TEST=8080" would be matched as "PORT=8080".

func WithTransform

func WithTransform(transform func(string) string) LoaderOption

WithTransform registers a custom transformation function for environment variables. The transformation function is used to modify environment variable keys before they are applied.

func WithTrimPrefix

func WithTrimPrefix(prefix string) LoaderOption

WithTrimPrefix removes the specified prefix from environment variable names before matching. Unlike WithPrefix, it does not filter variables.

func WithTrimSuffix

func WithTrimSuffix(suffix string) LoaderOption

WithTrimSuffix removes the specified suffix from environment variable names before matching. Unlike WithHasSuffix, it does not filter variables.

type Option

type Option func(*Options)

func WithDecodeUnset

func WithDecodeUnset() Option

WithDecodeUnset enables decoding unset environment variables. By default, unset environment variables are not decoded.

func WithDecodeUnsetTag

func WithDecodeUnsetTag(tag string) Option

WithDecodeUnsetTag sets the struct tag name used for decoding unset environment variables. The default tag name is "decodeunset".

func WithDecoder

func WithDecoder(iface any, f func(v any, value string) error) Option

WithDecoder registers a custom decoder function for a specific interface.

func WithDefaultTag

func WithDefaultTag(tag string) Option

WithDefaultTag sets the struct tag name used for default values. The default tag name is "default".

func WithDelimiter

func WithDelimiter(delim string) Option

WithDelimiter sets the delimiter used to separate slice/map elements in environment variable values. The default delimiter is ",".

func WithDelimiterTag

func WithDelimiterTag(tag string) Option

WithDelimiterTag sets the struct tag name used for the delimiter. The default tag name is "delim".

func WithDisableFallback

func WithDisableFallback() Option

WithDisableFallback enforces strict matching using the "env" tag. By default, it will try the field name, snake case field name, and all struct tags until a match is found.

func WithExpand

func WithExpand() Option

WithExpand is a global setting to expand environment variables in values. By default, environment variables are not expanded.

func WithExpandTag

func WithExpandTag(tag string) Option

WithExpandTag sets the struct tag name used for environment variable expansion. The default tag name is "expand".

func WithFileTag

func WithFileTag(tag string) Option

WithFileTag sets the struct tag name used for file paths. The default tag name is "file".

func WithInitAlways

func WithInitAlways() Option

WithInitAlways enables automatic initialization of nil pointers regardless of whether matching environment variables are found. By default they are initialized only when a matching environment variable is found.

func WithInitAny

func WithInitAny() Option

WithInitAny enables automatic initialization nil pointers if environment variables are found or if default values are provided. By default they are initialized only when a matching environment variable is found.

func WithInitNever

func WithInitNever() Option

WithInitNever disables automatic initialization of nil pointers By default they are initialized only when a matching environment variable is found.

func WithInitTag

func WithInitTag(tag string) Option

WithInitTag sets the struct tag name used for initialization mode. The default tag name is "init".

func WithKindParser

func WithKindParser(k reflect.Kind, f func(value string) (any, error)) Option

WithKindParser registers a custom parser function for a specific reflect.Kind. This allows extending the parser to support additional kinds beyond the built-in supported kinds.

func WithKindParsers

func WithKindParsers(parsers map[reflect.Kind]func(value string) (any, error)) Option

WithKindParsers registers multiple custom parser functions for specific reflect.Kinds. This allows extending the parser to support additional kinds beyond the built-in supported kinds. This is a convenience function for registering multiple kind parsers at once.

func WithLoader added in v0.2.0

func WithLoader(opts ...LoaderOption) Option

func WithNotEmpty

func WithNotEmpty() Option

WithNotEmpty is a global setting to validate that values are not empty. By default, empty values are not allowed.

func WithNotEmptyTag

func WithNotEmptyTag(tag string) Option

WithNotEmptyTag sets the struct tag name used for validating that values are not empty. The default tag name is "notempty".

func WithRequired

func WithRequired() Option

WithRequired is a global setting to validate that values are required. By default, fields are not required.

func WithSeparator

func WithSeparator(sep string) Option

WithSeparator sets the separator used for key-value pairs in map environment variable values. The default separator is ":".

func WithSeparatorTag

func WithSeparatorTag(tag string) Option

WithSeparatorTag sets the struct tag name used for the separator. The default tag name is "sep".

func WithTagName

func WithTagName(tag string) Option

WithTagName sets a custom struct tag name to override the default "env" tag.

func WithTypeParser

func WithTypeParser(t reflect.Type, f func(value string) (any, error)) Option

WithTypeParser registers a custom parser function for a specific type. This allows extending the parser to support additional types beyond the built-in supported types.

func WithTypeParsers

func WithTypeParsers(parsers map[reflect.Type]func(value string) (any, error)) Option

WithTypeParsers registers multiple custom parser functions for specific types. This allows extending the parser to support additional types beyond the built-in supported types. This is a convenience function for registering multiple type parsers at once.

type Options

type Options struct {
	Walker  *walker.Walker
	Loader  *loader.Loader
	Decoder *decoder.Decoder
	Parser  *parser.Parser
	Matcher *matcher.Matcher
}

func Build

func Build(opts ...Option) (*Options, error)

Directories

Path Synopsis
internal
tag
awssm module

Jump to

Keyboard shortcuts

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