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

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

帶有數據列表的 yaml 文件

帶有數據列表的 yaml 文件

Go
大話西游666 2022-06-27 15:12:00
全部,我確信這很容易,但有點掙扎——嘗試使用 gopkg.in/yaml.v3 編寫一個將在 Go 程序中使用的 yaml 文件。我需要定義服務器列表及其相關元數據。在 JSON 中這是一個相當簡單的過程,它是如何在 yaml 文件中處理的。Go 代碼結構如下。type Config struct {    Servers struct {        Servers struct {            ServerType string `yaml:"serverType"`            ServerPort int `yaml:"serverPort"`            Auth struct {                AuthType string `yaml:"auth"`                TLSKey  string `yaml:"tls"`            } `yaml:"auth"`        }`yaml:"server"`    } `yaml:"Servers"`}yaml 文件如下所示Servers:  server:    serverType: production    serverPort: 80    auth:      auth: no      tls:  server:    serverType: test    serverPort: 8080    auth:      auth: no      tls:我確信我錯過了一些相當明顯的東西 - 有什么智慧的話可以幫助我前進嗎?
查看完整描述

2 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

這是一個很好的在線資源,可以幫助您了解 YAML 配置以及如何生成兼容的 Go 結構:https ://yaml.to-go.online/


如果您想要一個服務器列表(切片) - 并且不需要通過鍵名查找映射 - 然后從這個 YAML 開始:


Servers:

  - serverType: production

    serverPort: 80

    auth:

      auth: no

      tls:

  - serverType: test

    serverPort: 8080

    auth:

      auth: no

      tls:

并使用上面的在線資源,產生這個結構:


type AutoGenerated struct {

    Servers []struct {

        ServerType string `yaml:"serverType"`

        ServerPort int    `yaml:"serverPort"`

        Auth       struct {

            Auth string      `yaml:"auth"`

            TLS  interface{} `yaml:"tls"`

        } `yaml:"auth"`

    } `yaml:"Servers"`

}

https://play.golang.org/p/726afn_I826


如果您希望能夠按名稱(即映射)索引服務器配置,那么可能是這個 YAML 模式:


Servers:

  production:

    serverPort: 80

    auth:

      auth: no

      tls:

  test:

    serverPort: 8080

    auth:

      auth: no

      tls:

這個手工結構:


type Config struct {

    Servers map[string]struct {

        ServerPort int `yaml:"serverPort"`

        Auth       struct {

            Auth string      `yaml:"auth"`

            TLS  interface{} `yaml:"tls"`

        } `yaml:"auth"`

    } `yaml:"Servers"`

}

https://play.golang.org/p/Cmvo0jxfZkd


查看完整回答
反對 回復 2022-06-27
?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

看起來您想要一組服務器。您不能在一個對象下重復相同的鍵:


Servers:

   - serverType: production

     ...

   - serverType: test

然后更改結構以匹配此:


type Config struct {

    Servers []struct {

            ServerType string `yaml:"serverType"`

            ServerPort int `yaml:"serverPort"`

            Auth struct {

                AuthType string `yaml:"auth"`

                TLSKey  string `yaml:"tls"`

            } `yaml:"auth"`

    } `yaml:"Servers"`

}


查看完整回答
反對 回復 2022-06-27
  • 2 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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