【发布时间】:2022-12-06 03:50:20
【问题描述】:
我有一个结构定义如下
type config struct {
Contexts map[string]Context `mapstructure:"contexts"`
CurrentContext string `mapstructure:"current-context"`
Tokens []Token `mapstructure:"tokens"`
}
type Context struct {
Endpoint string `mapstructure:"endpoint,omitempty"`
Token string `mapstructure:"token,omitempty"`
Platform string `mapstructure:"platform"`
Components []string `mapstructure:"components,omitempty"`
Channel string `mapstructure:"channel,omitempty"`
Version string `mapstructure:"version,omitempty"`
EnforcedProvider string `mapstructure:"enforced-provider,omitempty"`
}
我正在写一个 YAML 配置文件,如下所示
configObj.Contexts[contextName] = context
viper.Set("contexts", configObj.Contexts)
viper.Set("current-context", configObj.CurrentContext)
viper.Set("tokens", configObj.Tokens)
err = viper.WriteConfig()
if err != nil {
return err
}
我定义的mapstructure标签并没有写到YAML文件中,而是将字段名写成小写。这尤其是 EnforcedProvider 字段的问题,该字段写为 enforcedprovider 而不是 enforced-provider。
如何使用 mapstructure 标签?
【问题讨论】: