Skip to content

Allows custom values of hooks to be entered into a map - #36

Closed
baagod wants to merge 0 commit into
go-viper:mainfrom
baagod:main
Closed

baagod wants to merge 0 commit into
go-viper:mainfrom
baagod:main

Conversation

@baagod

@baagod baagod commented Jul 17, 2024 •

Copy link
Copy Markdown

When we want to convert the mapping value to a structure field, we can easily convert it by hook:

type Message struct {
	Content string    `json:"content"`
	Time    time.Time `json:"time"`
}

var result Message

decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
	DecodeHook: func(f reflect.Type, t reflect.Type, data any) (any, error) {
		if t == reflect.TypeOf(time.Time{}) {
			msgTime, _ := time.ParseInLocation(time.DateTime, data.(string), time.Local)
			return msgTime, nil
		}
		return data, nil
	},
	Result:  &result,
	TagName: "json",
})

input := map[string]any{"content": "testMsg", "time": "2024-07-17 11:09:23"}
_ = decoder.Decode(input)
// result => Message[Content="testMsg" Time=2024-07-17 11:09:23 +0800 CST]

However, when you need to convert the structure field values to 'map' in the same way, this doesn't work:

type Message struct {
	Content string    `json:"content"`
	Time    time.Time `json:"time"`
}

result := map[string]any{}
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
	DecodeHook: func(f reflect.Type, t reflect.Type, data any) (any, error) {
		if f == reflect.TypeOf(&time.Time{}) {
			msgTime, _ := data.(*time.Time)
			return msgTime.Format(time.DateTime), nil
		}
		return data, nil
	},
	Result:  &result,
	TagName: "json",
})

input := Message{"testMsg", time.Now()}
if err := decoder.Decode(input); err != nil {
	fmt.Println("err:", err)
}

fmt.Printf("%+v\n", result)

得到一个错误:err: 'time' expected a map, got 'string'.

该提交正是为了解决这个问题,现在执行上面的代码不会再报错,将输出:map[content:"testMsg" time:"2024-07-17 11:24:27"].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant