knadh / koanf

Simple, extremely lightweight, extensible, configuration management library for Go. Support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
MIT License
2.68k stars 149 forks source link

feature: unmarshal with defaults and required fields #321

Open thnk2wn opened 2 days ago

thnk2wn commented 2 days ago

It'd be great to have required and default attribute support when unmarshalling koanf config into structs.

While it might not be the primary focus of koanf, I think that unmarshalling config into structs is the primary way most want to reference the config values koanf holds.

Ensuring required configuration items are set and providing reasonable defaults when they're not is very common and we're used to the support from modules like kelseyhightower/envconfig. Without that there's a lot more tedious work to do before and after koanf loading.

I took a quick stab at merging this functionality from kelseyhightower/envconfig into a new unmarshal method in our forked repo. While it's only been quickly tested, the envconfig source is rock solid and I minimized changes for quick start. The performance could probably be improved. At any rate, it's here for reference if it's helpful for the feature intent and/or potential future implementation.

teamjobot/koanf/pull/2

qianlongzt commented 2 days ago

Try using https://github.com/go-playground/validator for validation.

Use go value for defaults

var config *Config = &Config{
    Port: "8989",
}

type Config struct {
    Port string 
}

k.UnmarshalWithConf("", config, koanf.UnmarshalConf{Tag: "tag"})