Go Viper 组件解码钩子

date
Apr 14, 2023
slug
GO-Viper-DecodeHook
status
Published
tags
知识分享
Golang
summary
使用自定义钩子函数解码Viper组件中的类型变量。
type
Post
category

背景

在使用Viper过程中,发现Viper默认将int解析为time.Duration后单位是ns。

解决

在viper.Unmarshal中可以带DecoderConfigOption,用DecodeHook包装DecodeHookFunc即为DecoderConfigOption,DecodeHookFunc就是interface{},Unmarshal带DecoderConfigOption示例:
如果有多个自定义钩子可以viper.Unmarshal(&ser,viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(myHookFun1,myHookFun2)))
这样就实现int到time.Duration的字段都变为time.Duration单位time.Second。
但是问题来了,在例子中ReadTimeout、WriteTimeout都被转换到以time.Second为单位的time.Duration。如果我想要WriteTimeout不转变为time.Second为单位而是time.MicroSecond呢?
只要把想要特殊处理的字段套上其他类型就行了,Show Code:
 
 
 

© Rysi 2018 - 2025