将字符串映射为UUID(通用唯一标识符)在Go语言中的实现方式。

huangapple go评论87阅读模式
英文:

Mapping string to UUID in go

问题

我正在使用mitchellh/mapstructuremap[string]interface{}映射到struct

有没有办法告诉mapstructurestring转换为uuid.UUID

map[string]interface{}:
{
    "id": "af7926b1-98eb-4c96-a2ba-7e429085b2ad",
	"title": "新标题",
}
struct
package entities

import (
	"github.com/google/uuid"
)

type Post struct {
	Id      uuid.UUID  `json:"id"`
	Title   string     `json:"title"`
}
英文:

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

答案1

得分: 3

你可以添加一个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))
    }
}
  • 来源:https://github.com/mitchellh/mapstructure/issues/236
  • 文档:https://pkg.go.dev/github.com/mitchellh/mapstructure#DecodeHookFunc
英文:

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

huangapple
  • 本文由 发表于 2022年2月10日 05:10:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/71056755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定