2 回答

TA貢獻1876條經驗 獲得超6個贊
實現允許格式(和注釋)的一種方法是使用模板引擎。
下面是一個運行示例,該示例生成一個帶有格式化 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
我相信有更好的方法來實現它,只是想展示一個快速的工作示例。

TA貢獻1757條經驗 獲得超8個贊
由于空行在 yaml 中沒有含義,因此默認庫不會創建它們,也不會在結構字段標記中公開執行此操作的選項。
但是,如果您希望對類型在 yaml 中的封送方式進行細粒度控制,則始終可以通過定義方法使其實現yaml.Marshaller
MarshalYAML() (interface{}, error)
- 2 回答
- 0 關注
- 154 瀏覽
添加回答
舉報