Giter Site home page Giter Site logo

Comments (2)

tburschka avatar tburschka commented on June 2, 2024 1

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.

rhnvrm avatar rhnvrm commented on June 2, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.