github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/aagent/util/mapstructure_hooks.go (about) 1 // Copyright (c) 2020-2022, R.I. Pienaar and the Choria Project contributors 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package util 6 7 import ( 8 "fmt" 9 "reflect" 10 11 "github.com/mitchellh/mapstructure" 12 ) 13 14 func ParseMapStructure(properties map[string]any, target any) error { 15 decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ 16 DecodeHook: mapstructure.ComposeDecodeHookFunc(mapstructure.StringToTimeDurationHookFunc(), StringSliceHookFunc), 17 Result: target, 18 WeaklyTypedInput: true, 19 }) 20 if err != nil { 21 return err 22 } 23 24 return decoder.Decode(properties) 25 } 26 27 func StringSliceHookFunc(f reflect.Type, t reflect.Type, data any) (any, error) { 28 if f.Kind() != reflect.Array { 29 return data, nil 30 } 31 32 if t != reflect.TypeOf([]string{}) { 33 return data, nil 34 } 35 36 var result []string 37 for _, env := range data.([]any) { 38 s, ok := env.(string) 39 if !ok { 40 return nil, fmt.Errorf("string slice is required") 41 } 42 result = append(result, s) 43 } 44 45 return result, nil 46 }