可以通过设置 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
提供的 DecoderConfig
和 NewDecoder
函数来创建一个解码器,然后将解码器应用到 viper 中读取的所有设置中,这样就能够避免 yml 标签被转换为小写了。
需要注意的是,如果你使用了其他的标签,则需要将其添加到 mapstructure.DecoderConfig
中的 TagName
字段中,例如:
decoderConfig := &mapstructure.DecoderConfig{
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
Result: &config,
TagName: "json", // 添加 json 标签
}