gpt4 book ai didi

go - 你如何在 Go YAML 中编码换行符?

转载 作者:行者123 更新时间:2023-12-04 03:25:45 24 4
gpt4 key购买 nike

在 golang CLI 中,我正在编程,我收集有关如何配置该工具的信息,并将其编码为 YAML 文件。但是,我不确定如何添加换行符以使文件更具可读性?

type Config struct {
Author string `yaml:"author"`
License string `yaml:"license"`
// Marhsal a line break here
Workspace string `yaml:"workspace"`
Description string `yaml:"description"`
// Marhsal a line break here
Target string `yaml:"target"`
}

最佳答案

一种允许格式(和注释)的实现方法是使用模板引擎。

这是一个运行示例,它生成一个带有格式化 yaml 的字符串,然后可以将其保存到 .yml 文件中。

不需要额外的库,模板包含在 go 文件中。

package main

import (
"bytes"
"fmt"
"text/template"
)

type Config struct {
Author string
License string
Workspace string
Description string
Target string
}

const cfg_template = `
conf:
author: {{ .Author }}
licence: {{ .License }}

workspace: {{ .Workspace }}
description: {{ .Description }}

# you can even add comments to the template
target: {{ .Target }}

# other hardcoded config
foo: bar

`

func generate(config *Config) string {
t, err := template.New("my yaml generator").Parse(cfg_template)

if err != nil {
panic(err)
}

buf := &bytes.Buffer{}
err = t.Execute(buf, config)

if err != nil {
panic(err)
}

return buf.String()
}

func main() {
c := Config{
Author: "Germanio",
License: "MIT",
Workspace: "/home/germanio/workspace",
Description: "a cool description",
Target: "/home/germanio/target",
}
yaml := generate(&c)

fmt.Printf("yaml:\n%s", yaml)
}

结果是这样的:

$ go run yaml_generator.go 
yaml:

conf:
author: Germanio
licence: MIT

workspace: /home/germanio/workspace
description: a cool description

# you can even add comments to the template
target: /home/germanio/target

# other hardcoded config
foo: bar

我确信有更好的方法来实现它,只是想展示一个快速的工作示例。

关于go - 你如何在 Go YAML 中编码换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67621557/

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