简体   繁体   中英

Mapping string to UUID in go

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"`
}

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))
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM