Skip to content
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

fix unmarshal dump.transformation from env variable #61

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/greenmask/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ func initConfig() {
decoderCfg := func(cfg *mapstructure.DecoderConfig) {
cfg.DecodeHook = mapstructure.ComposeDecodeHookFunc(
configUtils.ParamsToByteSliceHookFunc(),
configUtils.StringToStructHookFunc(),
configUtils.StringToSliceWithBracketHookFunc(),
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
)
Expand Down
57 changes: 57 additions & 0 deletions internal/utils/config/mapstructure_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,60 @@ func ParamsToByteSliceHookFunc() mapstructure.DecodeHookFunc {
}
}
}

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

raw := data.(string)
if raw == "" {
return []string{}, nil
}
var slice []json.RawMessage
err := json.Unmarshal([]byte(raw), &slice)
if err != nil {
return data, nil
}

var strSlice []string
for _, v := range slice {
strSlice = append(strSlice, string(v))
}
return strSlice, nil
}
}

func StringToStructHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if f.Kind() != reflect.String ||
(t.Kind() != reflect.Struct && !(t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.Struct)) {
return data, nil
}
raw := data.(string)
var val reflect.Value
// Struct or the pointer to a struct
if t.Kind() == reflect.Struct {
val = reflect.New(t)
} else {
val = reflect.New(t.Elem())
}

if raw == "" {
return val, nil
}
err := json.Unmarshal([]byte(raw), val.Interface())
if err != nil {
return data, nil
}
return val.Interface(), nil
}
}