gpt4 book ai didi

go - 将结构转换为YAML文件golang,如何避免yaml输出中的空引号?

转载 作者:行者123 更新时间:2023-12-01 22:26:33 25 4
gpt4 key购买 nike

我正在尝试使用struct产生以下YAML,

预期产量:

all:
hosts:
children:
master:
hosts:
// This is dynamic data coming from the slice.
192.168.99.123:
192.168.99.125:
worker:
hosts:
192.168.99.123:
192.168.99.125:
etcd:
hosts:
192.168.99.123:
192.168.99.125:
vars:
ansible_user: vagrant
ansible_ssh_private_key_file: "~/.ssh/id_rsa"

我的golang结构如下
type Inventory struct {
All *AnsibleInventory `json:"all"`
}

// AnsibleInventory defines ansible inventory file struct
type AnsibleInventory struct {
Hosts string `json:"hosts"`
Children *HostGroup `json:"children"`
Vars *Vars `json:"vars"`
}

type HostGroup struct {
Master *Hosts `json:"master"`
Worker *Hosts `json:"worker"`
Etcd *Hosts `json:"etcd"`
}

type Hosts struct {
Hosts map[string]string `json:"hosts,omitempty"`
}

type Vars struct {
User string `json:"ansible_user"`
SshPrivateKeyFile string `json:"ansible_ssh_private_key_file"`
}

我正在按以下方式初始化struct,
    elementMap := make(map[string]string)
for _, ip := range p.MasterIPs {
elementMap[ip] = "" // I tried using slice this is definitely not expected
}

ansibleInventory := &Inventory{
&AnsibleInventory{Children: &HostGroup{
Master: &Hosts{
elementMap,
},
Worker: &Hosts{
elementMap,
},
Etcd: &Hosts{
elementMap,
},
}, Vars: &Vars{
User: p.Username,
SshPrivateKeyFile: p.PrivateKeyPath,
}}}

b, err := yaml.Marshal(ansibleInventory)

filename:= "/tmp/filename"

_, err = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
err = ioutil.WriteFile(filename, b, 0644)

产生的输出看起来像这样,
all:
children:
etcd:
hosts:
// I want to avoid this empty quote
192.168.99.123: ""
192.168.99.125: ""
master:
hosts:
192.168.99.123: ""
192.168.99.125: ""
worker:
hosts:
192.168.99.123: ""
192.168.99.125: ""
// Same here aovid this empty quote
hosts: ""
vars:
ansible_ssh_private_key_file: ~/.ssh/id_rsa
ansible_user: vagrant

最佳答案

您需要在每个结构中指定yaml标记而不是json:

type Inventory struct {
All *AnsibleInventory `yaml:"all"` // not `json:"all"`
}

关于go - 将结构转换为YAML文件golang,如何避免yaml输出中的空引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59690652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com