英文:
Mapping string to UUID in go
问题
我正在使用mitchellh/mapstructure将map[string]interface{}
映射到struct
。
有没有办法告诉mapstructure
将string
转换为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))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论