config

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFlags

func AddFlags(defaultConfig any, v *viper.Viper, f *pflag.FlagSet, hooks ...EncodeHookFunc) error

AddFlags adds flags to the given viper and flag set.

It uses the following struct field tags - `flag` struct field tag to get the flag name, environment variable name, description, and short flag. - `env` struct field tag to get the environment variable name. - `desc` struct field tag to get the description. - `short` struct field tag to get the short flag. - `key` struct field tag to get the key.

It sets the default values as set on the defaultConfig object.

func Env

func Env(cfg any, hooks ...EncodeHookFunc) (map[string]string, error)

Env returns a map of environment variables for the given configuration object. It uses the `env` struct field tag to get the environment variable name.

Example (Basic)
type User struct {
	Name string `env:"NAME"`
	Age  int    `env:"AGE"`
}

env, err := Env(&User{
	Name: "John",
	Age:  30,
})
if err != nil {
	panic(err)
}

fmt.Printf("NAME=%s\n", env["NAME"])
fmt.Printf("AGE=%s\n", env["AGE"])
Output:
NAME=John
AGE=30
Example (CustomEncodeHook)
type MyCustomType int

customEncodeHook := func(val reflect.Value) (reflect.Value, error) {
	if val.Type() == reflect.TypeOf(MyCustomType(0)) {
		return reflect.ValueOf(fmt.Sprintf("my great type: %d", val.Interface())), nil
	}
	return val, nil
}

type MyType struct {
	MyCustomField MyCustomType `env:"MY_CUSTOM_FIELD"`
}

env, err := Env(&MyType{
	MyCustomField: MyCustomType(1),
}, customEncodeHook)
if err != nil {
	panic(err)
}

fmt.Printf("MY_CUSTOM_FIELD=%s\n", env["MY_CUSTOM_FIELD"])
Output:
MY_CUSTOM_FIELD=my great type: 1
Example (DefaultEncodeHook)
type User struct {
	Name string
	Age  int
	Role Role
}

// Role implements fmt.Stringer, so it will be encoded as a string
env, err := Env(&User{
	Name: "John",
	Age:  30,
	Role: Role(1),
})
if err != nil {
	panic(err)
}

fmt.Printf("NAME=%s\n", env["NAME"])
fmt.Printf("AGE=%s\n", env["AGE"])
fmt.Printf("ROLE=%s\n", env["ROLE"])
Output:
NAME=John
AGE=30
ROLE=user
Example (Nested)
type User struct {
	Name string `env:"NAME"`
	Age  int    `env:"AGE"`
}

type Organization struct {
	Admin *User `env:"ADMIN"`
}

env, err := Env(&Organization{
	Admin: &User{
		Name: "John",
		Age:  30,
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("ADMIN_NAME=%s\n", env["ADMIN_NAME"])
fmt.Printf("ADMIN_AGE=%s\n", env["ADMIN_AGE"])
Output:
ADMIN_NAME=John
ADMIN_AGE=30
Example (NestedWithDefaultEnvNaming)
type User struct {
	Name string
	Age  int
}

type Organization struct {
	AdminA *User
	AdminB *User
}

env, err := Env(&Organization{
	AdminA: &User{
		Name: "John",
		Age:  30,
	},
	AdminB: &User{
		Name: "Jane",
		Age:  31,
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("ADMINA_NAME=%s\n", env["ADMINA_NAME"])
fmt.Printf("ADMINA_AGE=%s\n", env["ADMINA_AGE"])
fmt.Printf("ADMINB_NAME=%s\n", env["ADMINB_NAME"])
fmt.Printf("ADMINB_AGE=%s\n", env["ADMINB_AGE"])
Output:
ADMINA_NAME=John
ADMINA_AGE=30
ADMINB_NAME=Jane
ADMINB_AGE=31
Example (NestedWithSkipTag)
type User struct {
	Name string
	Age  int
}

type Organization struct {
	AdminA *User `env:"-"`
	AdminB *User
}

env, err := Env(&Organization{
	AdminA: &User{
		Name: "John",
		Age:  30,
	},
	AdminB: &User{
		Name: "Jane",
		Age:  31,
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("NAME=%s\n", env["NAME"])
fmt.Printf("AGE=%s\n", env["AGE"])
fmt.Printf("ADMINB_NAME=%s\n", env["ADMINB_NAME"])
fmt.Printf("ADMINB_AGE=%s\n", env["ADMINB_AGE"])
Output:
NAME=John
AGE=30
ADMINB_NAME=Jane
ADMINB_AGE=31

func FlagDesc

func FlagDesc(desc, envVar string) string

FlagDesc returns the description of the flag

func GlobalDecodeHook

func GlobalDecodeHook() mapstructure.DecodeHookFunc

GlobalDecodeHook returns the global decode hook

func Marshal added in v0.9.1

func Marshal(cfg any, hooks ...EncodeHookFunc) ([]byte, error)

Marshal marshals a configuration object to JSON using the `key` tag for field names. It applies encode hooks to transform values before marshaling (e.g., converting enums to strings).

func NewViper

func NewViper(opts ...viper.Option) *viper.Viper

NewViper creates a new viper instance with the given options.

func NilStrToNilDecodeHookFunc

func NilStrToNilDecodeHookFunc(nilStr string) mapstructure.DecodeHookFunc

NilStrToNilDecodeHookFunc is a mapstructure decode hook that converts a string to a nil

func PtrToValueDecodeHookFunc

func PtrToValueDecodeHookFunc() mapstructure.DecodeHookFunc

PtrToValueDecodeHookFunc is a mapstructure decode hook that converts a pointer to a value

func RegisterGlobalDecodeHooks

func RegisterGlobalDecodeHooks(hks ...mapstructure.DecodeHookFunc)

RegisterGlobalDecodeHooks registers the given decode hooks to the global decode hooks

func RegisterGlobalEncodeHooks

func RegisterGlobalEncodeHooks(hks ...EncodeHookFunc)

RegisterGlobalEncodeHooks registers the given encode hooks to the global encode hooks

func StringToMapDecodeHookFunc added in v0.8.0

func StringToMapDecodeHookFunc(sep string) mapstructure.DecodeHookFunc

StringToMapDecodeHookFunc is a mapstructure decode hook that converts a string to a map. The string format is "key1:value1 key2:value2" where sep is the separator between pairs (default " "). It supports nested maps using additional colon-separated keys: "key:nestedKey:value". The nesting depth is determined by the target type (e.g. map[string]map[string]int has depth 2).

func StringToWeakSliceDecodeHookFunc

func StringToWeakSliceDecodeHookFunc(sep string) mapstructure.DecodeHookFunc

StringToWeakSliceHookFunc is a mapstructure decode hook that converts a string to a slice of strings. It is set by default in the viper.Viper package so we declare it here for custom viper.Viper instances.

func TagNameDecoderConfigOption

func TagNameDecoderConfigOption(name string) viper.DecoderConfigOption

TagNameDecoderConfigOption is a viper.DecoderConfigOption that sets the tag name for the decoder.

func Unmarshal

func Unmarshal(cfg any, v *viper.Viper, opts ...viper.DecoderConfigOption) error

Unmarshal unmarshals the config into a Struct. Make sure that the tags on the fields of the structure are properly set.

func UnmarshalKey

func UnmarshalKey(key string, rawVal any, v *viper.Viper, opts ...viper.DecoderConfigOption) error

UnmarshalKey takes a single key and unmarshals it into a Struct.

Types

type BoolFlag

type BoolFlag struct {
	ViperKey     string
	Name         string
	Shorthand    string
	Env          string
	Description  string
	DefaultValue any
}

BoolFlag is a flag that can be used to add a bool flag

func (*BoolFlag) Add

func (flag *BoolFlag) Add(v *viper.Viper, f *pflag.FlagSet)

Add adds the flag to the given viper and flag set

type EncodeHookFunc

type EncodeHookFunc func(reflect.Value) (reflect.Value, error)

EncodeHookFunc is a function that can be used to encode a value

func CombineHooks

func CombineHooks(hooks ...EncodeHookFunc) EncodeHookFunc

CombineHooks combines the given encode hooks into a single encode hook

func GlobalEncodeHook

func GlobalEncodeHook() EncodeHookFunc

GlobalEncodeHook returns the global encode hook

func StringerHook

func StringerHook() EncodeHookFunc

StringerHook is a mapstructure encode hook that converts a value to a string

type FieldInfo

type FieldInfo struct {
	FieldParts []string            // Field name parts
	TagParts   map[string][]string // Map of inspected tag name to the tag values (each slice has the same length as the FieldParts slice)
	Value      reflect.Value       // Actual value of the field in the struct, possibly zeroed if the original value was unset (nil or within a nested nil struct field)
	Processed  reflect.Value       // Value after processing (in particular after EncodeHook has been applied), if not processed, it is the same as Value
	Encoded    string              // Encoded value of the field value
	IsNil      bool                // Whether the orignal value was nil or nested within a nil struct field
}

FieldInfo represents information about a field in a struct

type Flag

type Flag struct {
	ViperKey     string
	Env          string
	Flag         *pflag.Flag
	DefaultValue any
}

Flag is a flag that can be used to add a flag

func (*Flag) Add

func (flag *Flag) Add(v *viper.Viper, f *pflag.FlagSet)

Add adds the flag to the given viper and flag set

type Inspector

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

Inspector is the main struct for inspecting a value

func NewInspector

func NewInspector(cfg *InspectorConfig) *Inspector

NewInspector creates a new Inspector

func (*Inspector) Inspect

func (i *Inspector) Inspect(c any) (map[string]*FieldInfo, error)

Inspect inspects the given value and all its fields recursively It returns a map of field information where keys are the nested field names joined by "."

type InspectorConfig

type InspectorConfig struct {
	TagNames   []string       // List of tag names to inspect
	EncodeHook EncodeHookFunc // Hook to apply to the value before encoding
	IncludeNil bool           // Whether to perform inspection even if a nil field is encountered
}

InspectorConfig is the configuration for the Inspector

type IntFlag

type IntFlag struct {
	ViperKey     string
	Name         string
	Shorthand    string
	Env          string
	Description  string
	DefaultValue any
}

IntFlag is a flag that can be used to add an int flag

func (*IntFlag) Add

func (flag *IntFlag) Add(v *viper.Viper, f *pflag.FlagSet)

Add adds the flag to the given viper and flag set

type StringArrayFlag

type StringArrayFlag struct {
	ViperKey     string
	Name         string
	Shorthand    string
	Env          string
	Description  string
	DefaultValue any
}

StringArrayFlag is a flag that can be used to add a string array flag

func (*StringArrayFlag) Add

func (flag *StringArrayFlag) Add(v *viper.Viper, f *pflag.FlagSet)

Add adds the flag to the given viper and flag set

type StringFlag

type StringFlag struct {
	ViperKey     string
	Name         string
	Shorthand    string
	Env          string
	Description  string
	DefaultValue any
}

StringFlag is a flag that can be used to add a string flag

func (*StringFlag) Add

func (flag *StringFlag) Add(v *viper.Viper, f *pflag.FlagSet)

Add adds the flag to the given viper and flag set

Jump to

Keyboard shortcuts

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