Comments (2)
I finally solved this. First approach was a custom provider, but i swapped to a custom decode hook:
https://github.com/tburschka/koanf-default-value/blob/main/decodehooks/defaults/defaults.go
package defaults
import (
"reflect"
"strings"
"github.com/go-viper/mapstructure/v2"
)
func Defaults(keyTag string, defaultTag string) mapstructure.DecodeHookFunc {
return func(f reflect.Value, t reflect.Value) (interface{}, error) {
tType := t.Type()
if tType.Kind() == reflect.Struct {
for i := 0; i < tType.NumField(); i++ {
setDefault(f, tType.Field(i), keyTag, defaultTag)
}
}
return f.Interface(), nil
}
}
func setDefault(f reflect.Value, t reflect.StructField, keyTag string, defaultTag string) {
if f.Kind() == reflect.Map {
key, _, _ := strings.Cut(t.Tag.Get(keyTag), ",")
val, ok := t.Tag.Lookup(defaultTag)
if !ok {
return
}
// check for key in the map
for _, e := range f.MapKeys() {
// key found, already set, nothing to do
if key == e.String() {
return
}
}
fVal := reflect.ValueOf(val)
// special handling for empty/missing structs
tType := t.Type
if tType.Kind() == reflect.Struct {
// create an empty map
fVal = reflect.ValueOf(map[string]any{})
for i := 0; i < tType.NumField(); i++ {
setDefault(fVal, tType.Field(i), keyTag, defaultTag)
}
}
// add missing key with default to the map
f.SetMapIndex(reflect.ValueOf(key), fVal)
}
}
it iterates over the structs and set the defaults. Note that this decodehook should be the first in the order:
config := &Config{}
_ = k.UnmarshalWithConf("", config, koanf.UnmarshalConf{
Tag: "yaml",
DecoderConfig: &mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(
defaults.Defaults("yaml", "default"),
mapstructure.StringToTimeDurationHookFunc(),
stringtoslice.StringToSlice(),
stringtomap.StringToMap(),
),
Metadata: nil,
Result: config,
WeaklyTypedInput: true,
},
})
Also, it's important, that you set the defaults for slices []
and structs {}
if you want the decode hook to handle them.
Finally, since i use two sources, the default merge approach is not working, so i needed a custom merge func.
I use mergo with the WithSliceDeepCopy option.
import "dario.cat/mergo"
// [...]
_ = k.Load(file.Provider(name), yaml.Parser())
_ = k.Load(env2json.Provider(configEnvPrefix, configEnvDelim, func(s string) string {
return strings.ToLower(strings.TrimPrefix(s, configEnvPrefix+configEnvDelim))
}), json.Parser(), koanf.WithMergeFunc(func(src, dest map[string]interface{}) error {
return mergo.Merge(&dest, src, mergo.WithSliceDeepCopy)
}))
I've created tests for all these cases (https://github.com/tburschka/koanf-default-value/blob/main/config_test.go). It works like a charm. I keep it online so in case anyone needs this, he can use it...
from koanf.
I'm not sure if it fully solves your requirement of using struct tags, but maybe you can utilize the structs package to load the default config.
Ref:
https://github.com/knadh/koanf/blob/master/README.md?plain=1#L516-L538
So, how it can look like is this:
// hardcode it
var DefaultConfig MyConfig = DefaultConfig{
...
}
// or
func initDefaults() MyConfig {
myConf := MyConfig{}
if err := defaults.Set(&obj); err != nil {
...
}
return myConf
}
func InitConfig(fpath string) MyConfig {
// Load defaults from hardcoded struct.
k.Load(structs.Provider(DefaultConfig))
// or
// use the defaults package
k.Load(structs.Provider(initDefaults()))
// Override from file.
k.Load(toml.Provider(fpath))
// Override config struct with cli flags
k.Load(pflag.Provider())
}
from koanf.
Related Issues (20)
- Is it possible to load config to the slice of structs? HOT 4
- How to stop file watcher? HOT 3
- Is it possible to define a parameter reference another parameter in mock.toml file? HOT 1
- How to retrieve/print the final YAML string after YAML files are loaded and merged? HOT 5
- Alternativ to pflag? HOT 4
- basicflag Provider does not exclude default values HOT 3
- Why not create new file when file not exists. HOT 1
- Read enviroments secrets from github HOT 2
- Can not parse environment variable HOT 1
- Switch from mitchellh/mapstructure to go-viper/mapstructure HOT 14
- Can't unmarshall env variable with multiple words
- Support for merging slices HOT 2
- File watching error when saving with vi/vim or neovim HOT 1
- How to populate a map[string]string from environment variables HOT 1
- When loading with providers/env, koanf.Unmarshal doesn't work. HOT 5
- koanf.Unmarshal doesn't work when loaded with env provider HOT 2
- posflag provider overrides values even if flags are not set for special delimiters HOT 1
- Convert non-string type to string in StringMap() HOT 1
- feature: search file HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from koanf.