登录
首页 >  Golang >  Go问答

使用 Golang 生成 YAML 文件

来源:stackoverflow

时间:2024-03-06 13:48:25 371浏览 收藏

大家好,我们又见面了啊~本文《使用 Golang 生成 YAML 文件》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

请帮助创建正确的 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 结构中需要一个数组。然后在填充数据时,创建一个新组并附加到配置。

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))
}

您还需要 group 的数组/切片,以便您的字段“组”可以具有类型 []group[]group。使用它自己的结构来做到这一点。

类似于:

type group struct {
    Name string `yaml:"name"`
    Targets []string `yaml:"targets"`
}

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

今天关于《使用 Golang 生成 YAML 文件》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>