亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Viper 在解組時不考慮我的結構中的 yaml 標簽

Viper 在解組時不考慮我的結構中的 yaml 標簽

Go
慕的地8271018 2023-06-26 17:34:20
當我使用Unmarshalviper 的方法用 yaml 文件中的值填充我的配置結構時,一些結構字段變成了空!我這樣做:viper.SetConfigType("yaml")viper.SetConfigName("config")viper.AddConfigPath("/etc/myapp/")viper.AddConfigPath(".")err := viper.ReadInConfig()// error checking ...conf := &ConfYaml{}err = viper.Unmarshal(conf)// error checking ...我的結構是這樣的:type ConfYaml struct {    Endpoints SectionStorageEndpoint `yaml:"endpoints"`}type SectionStorageEndpoint struct {    URL       string `yaml:"url"`    AccessKey string `yaml:"access_key"`    SecretKey string `yaml:"secret_key"`    UseSSL    bool   `yaml:"use_ssl"`    Location  string `yaml:"location"`}這里url和location字段在 yaml 文件中填充了正確的值,但其他字段為空!很想知道當我嘗試打印如下字段時:viper.Get("endpoints.access_key")它在 yaml 文件中打印正確的值并且不為空!
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

終于找到了解決方案,更改yaml:標簽mapstructure:即可解決問題。

看來 viper 無法解組我的.yaml文件中沒有相同鍵名的字段。就像問題中的access_keyand一樣,導致結構體字段位于 where和。secret_keyAccessKeySecretKey

location但是像和that這樣的字段url在結構體和文件中具有相同的名稱.yaml,并且沒有問題。

正如這個問題所說:

問題是viper使用 MapStructure 包將配置映射解組到結構。它不支持 yaml 包使用的 yaml 標簽。

因此,更改yaml:標簽中的 即可mapstructure:解決問題。


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號