ZBLOG

viper 中禁止 yml 标签被转换为小写

可以通过设置 viper 的 Unmarshal 函数中的参数 mapstructure.DecodeHook 来禁止 yml 标签被转换为小写。具体操作如下:

import (
    "github.com/spf13/viper"
    "github.com/mitchellh/mapstructure"
)

type Config struct {
    Name string `mapstructure:"name" yaml:"name"`
    Port int `mapstructure:"port" yaml:"port"`
}

func main() {
    viper.SetConfigFile("config.yml")
    viper.ReadInConfig()

    var config Config
    decoderConfig := &mapstructure.DecoderConfig{
        DecodeHook: mapstructure.StringToTimeDurationHookFunc(), // 可选的解码钩子函数
        Result:     &config,
    }
    decoder, err := mapstructure.NewDecoder(decoderConfig)
    if err != nil {
        // 处理错误
    }
    err = decoder.Decode(viper.AllSettings())
    if err != nil {
        // 处理错误
    }

    // 使用 config
}

在上面的代码中,我们使用了第三方库 github.com/mitchellh/mapstructure 提供的 DecoderConfigNewDecoder 函数来创建一个解码器,然后将解码器应用到 viper 中读取的所有设置中,这样就能够避免 yml 标签被转换为小写了。

需要注意的是,如果你使用了其他的标签,则需要将其添加到 mapstructure.DecoderConfig 中的 TagName 字段中,例如:

decoderConfig := &mapstructure.DecoderConfig{
    DecodeHook:  mapstructure.StringToTimeDurationHookFunc(),
    Result:      &config,
    TagName:     "json", // 添加 json 标签
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1354

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?