【问题标题】:mapstructure tags not used by Viper when writing to YAML写入 YAML 时 Viper 未使用的 mapstructure 标签
【发布时间】: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 标签?

【问题讨论】:

    标签: go viper-go


    【解决方案1】:

    该文档在其Unmarshaling section 中提及了 mapstructure 标签,但在其WriteConfig section 中未提及。

    看起来 WriteConfig 将通过默认编码器之一:


    如果你知道你只会从 yaml 文件读取/写入,最简单的方法是在你的结构上设置 yaml 标签(遵循 gopkg.in/yaml.v2 包的文档):

    type config {
        Contexts       map[string]Context `yaml:"contexts"`
        CurrentContext string             `yaml:"current-context"`
        Tokens         []Token            `yaml:"tokens"`
    }
    
    type Context struct {
        Endpoint         string   `yaml:"endpoint,omitempty"`
        Token            string   `yaml:"token,omitempty"`
        Platform         string   `yaml:"platform"`
        Components       []string `yaml:"components,omitempty"`
        Channel          string   `yaml:"channel,omitempty"`
        Version          string   `yaml:"version,omitempty"`
        EnforcedProvider string   `yaml:"enforced-provider,omitempty"`
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 2019-02-13
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多