Skip to content

Commit

Permalink
Add map string bool decode hook
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelreiswildlife committed Sep 21, 2023
1 parent fd4ee1d commit ec879c8
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,15 @@ func DecodeHook() viper.DecoderConfigOption {
decodeHook := mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
StringToMapHookFunc(),
StringToMapStringHookFunc(),
StringToMapBoolHookFunc(),
)

return viper.DecodeHook(decodeHook)

}

func StringToMapHookFunc() mapstructure.DecodeHookFunc {
func StringToMapStringHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
Expand All @@ -67,3 +68,28 @@ func StringToMapHookFunc() mapstructure.DecodeHookFunc {
return m, err
}
}

func StringToMapBoolHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if f.Kind() != reflect.String || t.Kind() != reflect.Map {
return data, nil
}

if t.Key().Kind() != reflect.String || t.Elem().Kind() != reflect.Bool {
return data, nil
}

raw := data.(string)
if raw == "" {
return map[string]bool{}, nil
}

m := map[string]bool{}
err := json.Unmarshal([]byte(raw), &m)
return m, err
}
}

0 comments on commit ec879c8

Please sign in to comment.