-
Notifications
You must be signed in to change notification settings - Fork 31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature request: custom type unmarshalling #26
Comments
Hey, this is a great suggestion! Would make configs look a lot nicer :) We could add a custom mapstructure type StringUnmarshaler interface {
UnmarshalString(s string) error
}
func (l *ListenerType) UnmarshalString(s string) error {
switch strings.ToLower(s) {
case "unix":
*l = ListenerUnix
...
}
return nil
}
func StringToStringUnmarshalerHook() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if reflect.PointerTo(t).Implements(reflect.TypeOf((*StringUnmarshaler)(nil)).Elem()) {
val := reflect.New(t).Interface()
if unmarshaler, ok := val.(StringUnmarshaler); ok {
err := unmarshaler.UnmarshalString(data.(string))
if err != nil {
return nil, err
}
return reflect.ValueOf(val).Elem().Interface(), nil
}
}
return data, nil
}
}
// during map structure decoder init
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: &cfg,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
StringToStringUnmarshalerHook(),
),
}) WDYT? |
I tested it on my local fork of fig and it works like a charm. Thanks for the quick turnaround! Looking forward to use this. |
If you'd like to add this please open a PR and I'll gladly review. |
PR #29 created |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First of all, I love fig. It's such a versatile tool, thanks for this!
I was wondering if there would be a posibility to add config parsing/unmarshaling for custom types, like
encode/json
allows to provide aUnmarshalJSON()
method. This would help i. e. with custom "enums" type that are set up viaiota
.Here is an example:
Let's say I have a custom type
ListenerType
and I pre-define 3 types via const:In my config struct, I would then define my config setting with the corresponding
ListenerType
and a default value:By default this would of course not work, as the default or provided setting in the config file would be a string, not an uint. But here comes my request into play. fig defines an interface like this:
and checks if the corresponding type provides a method that satisfies this interface. For my example it could look like this:
This way, I can keep my
iota
type but fill the values via fig with the actual string values instead of the user having to provide "0", "1" or "2".Hope this makes sense and is something you would consider adding.
The text was updated successfully, but these errors were encountered: