Documentation
¶
Index ¶
- func MustParse(cfg any, opts ...Option)
- func MustParseAs[T any](opts ...Option) T
- func Parse(cfg any, opts ...Option) error
- func ParseAs[T any](opts ...Option) (T, error)
- type LoaderOption
- func WithDotEnvSource(path string) LoaderOption
- func WithFilter(filter func(string) bool) LoaderOption
- func WithHasMatch(pattern regexp.Regexp) LoaderOption
- func WithHasPrefix(prefix string) LoaderOption
- func WithHasSuffix(suffix string) LoaderOption
- func WithMapEnvSource(envs map[string]string) LoaderOption
- func WithOSEnvSource() LoaderOption
- func WithPrefix(prefix string) LoaderOption
- func WithSource(source loader.Source) LoaderOption
- func WithSources(sources ...loader.Source) LoaderOption
- func WithSuffix(suffix string) LoaderOption
- func WithTransform(transform func(string) string) LoaderOption
- func WithTrimPrefix(prefix string) LoaderOption
- func WithTrimSuffix(suffix string) LoaderOption
- type Option
- func WithDecodeUnset() Option
- func WithDecodeUnsetTag(tag string) Option
- func WithDecoder(iface any, f func(v any, value string) error) Option
- func WithDefaultTag(tag string) Option
- func WithDelimiter(delim string) Option
- func WithDelimiterTag(tag string) Option
- func WithDisableFallback() Option
- func WithExpand() Option
- func WithExpandTag(tag string) Option
- func WithFileTag(tag string) Option
- func WithInitAlways() Option
- func WithInitAny() Option
- func WithInitNever() Option
- func WithInitTag(tag string) Option
- func WithKindParser(k reflect.Kind, f func(value string) (any, error)) Option
- func WithKindParsers(parsers map[reflect.Kind]func(value string) (any, error)) Option
- func WithLoader(opts ...LoaderOption) Option
- func WithNotEmpty() Option
- func WithNotEmptyTag(tag string) Option
- func WithRequired() Option
- func WithSeparator(sep string) Option
- func WithSeparatorTag(tag string) Option
- func WithTagName(tag string) Option
- func WithTypeParser(t reflect.Type, f func(value string) (any, error)) Option
- func WithTypeParsers(parsers map[reflect.Type]func(value string) (any, error)) Option
- type Options
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MustParseAs ¶
MustParseAs is like ParseAs but panics if an error occurs during parsing.
func Parse ¶
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
Types ¶
type LoaderOption ¶ added in v0.2.0
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 ¶
WithDecodeUnsetTag sets the struct tag name used for decoding unset environment variables. The default tag name is "decodeunset".
func WithDecoder ¶
WithDecoder registers a custom decoder function for a specific interface.
func WithDefaultTag ¶
WithDefaultTag sets the struct tag name used for default values. The default tag name is "default".
func WithDelimiter ¶
WithDelimiter sets the delimiter used to separate slice/map elements in environment variable values. The default delimiter is ",".
func WithDelimiterTag ¶
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 ¶
WithExpandTag sets the struct tag name used for environment variable expansion. The default tag name is "expand".
func WithFileTag ¶
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 ¶
WithInitTag sets the struct tag name used for initialization mode. The default tag name is "init".
func WithKindParser ¶
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 ¶
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 ¶
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 ¶
WithSeparator sets the separator used for key-value pairs in map environment variable values. The default separator is ":".
func WithSeparatorTag ¶
WithSeparatorTag sets the struct tag name used for the separator. The default tag name is "sep".
func WithTagName ¶
WithTagName sets a custom struct tag name to override the default "env" tag.
func WithTypeParser ¶
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 ¶
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.