Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading