首页 > 解决方案 > 带有数据列表的 yaml 文件

问题描述

全部,

我确信这很容易,但有点挣扎——尝试使用 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:

我确信我错过了一些相当明显的东西 - 有什么智慧的话可以帮助我前进吗?

谢谢

标签: goyaml

解决方案


看起来您想要一组服务器。您不能在一个对象下重复相同的键:

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"`
}

推荐阅读