go - 通过Golang形成YAML

标签 go yaml

请帮助创建正确的YAML结构。
我需要收到以下内容:

groups:
  - name: Group1
    targets:
    - host1
    - host2
  - name: Group2
    targets:
    - host1
    - host2
而且我编写了下一个有效但无法正确执行的代码:
type YamlConfig struct {
    Groups struct {
            Name string `yaml:"name"`
            Targets []string `yaml:"targets"`
    } `yaml:"groups"`
}

var config YamlConfig
var hosts []string = []string{"host1", "host2"}
for host := range hosts {
    config.Groups.Name = "Group"+strconv.Itoa(host)
    config.Groups.Targets = hosts
}

y, err := yaml.Marshal(config)
if err != nil {
    fmt.Printf("Marshal: %v", err)
}

fmt.Println(string(y))
但是这个例子只构成了这个结构:
groups:
  name: Group1
  targets:
  - host1
  - host2
请帮助以正确的方式获得第一个结果

最佳答案

您需要稍微改变一下结构。由于Group是一个列表,因此需要在go struct中使用一个数组。然后,在填充数据时,创建一个新组并追加到config。

package main

import (
    "fmt"
    "strconv"

    "gopkg.in/yaml.v2"
)

func main() {
    type Group struct {
        Name    string   `yaml:"name"`
        Targets []string `yaml:"targets"`
    }

    type YamlConfig struct {
        Groups []Group `yaml:"groups"`
    }

    var config YamlConfig
    var hosts []string = []string{"host1", "host2"}
    for host := range hosts {
        var group Group
        group.Name = "Group" + strconv.Itoa(host)
        group.Targets = hosts
        config.Groups = append(config.Groups, group)
    }

    y, err := yaml.Marshal(config)
    if err != nil {
        fmt.Printf("Marshal: %v", err)
    }

    fmt.Println(string(y))
}

关于go - 通过Golang形成YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63782623/

相关文章:

yaml - 基于 Jekyll 的博客中显示的日期错误

c++ - 如何在 OpenCV 中以编程方式在 YAML 中编写注释?

http - 发送带有 body 的 HEAD http 请求导致 net/http 错误

amazon-web-services - AWS 预签名 url acl 公共(public)读取无效签名

mongodb - 自定义 mgo upsert 操作

python - 修复 yaml 文件中的 linting 错误

yaml - ruamel 压缩注释并注入(inject) 0x07

gorilla mux 路由器处理程序

json - 在 Hugo 中用字符串按键查找数据

ruby-on-rails - Rails 语言环境文件无法加载