I'm using mitchellh/mapstructure to map from map[string]interface{}
to struct
Is there any way to tell mapstructure
to convert string
to uuid.UUID
?
map[string]interface{}
:
{
"id": "af7926b1-98eb-4c96-a2ba-7e429085b2ad",
"title": "new title",
}
struct
package entities
import (
"github.com/google/uuid"
)
type Post struct {
Id uuid.UUID `json:"id"`
Title string `json:"title"`
}
CodePudding user response:
You could add a DecodeHookFunc
:
func decode(input, output interface{}) error {
config := &mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(
stringToUUIDHookFunc(),
),
Result: &output,
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
func stringToUUIDHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(uuid.UUID{}) {
return data, nil
}
return uuid.Parse(data.(string))
}
}