亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go YAML 中封送換行符?

如何在 Go YAML 中封送換行符?

Go
慕村9548890 2022-08-30 22:02:32
在golang CLI中,我正在編程,我收集有關如何配置該工具的信息,并將其作為YAML文件進行marhsal。但是,我不確定如何添加換行符以使文件更具可讀性?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"`}
查看完整描述

2 回答

?
HUX布斯

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

我相信有更好的方法來實現它,只是想展示一個快速的工作示例。


查看完整回答
反對 回復 2022-08-30
?
陪伴而非守候

TA貢獻1757條經驗 獲得超8個贊

由于空行在 yaml 中沒有含義,因此默認庫不會創建它們,也不會在結構字段標記中公開執行此操作的選項。

但是,如果您希望對類型在 yaml 中的封送方式進行細粒度控制,則始終可以通過定義方法使其實現yaml.MarshallerMarshalYAML() (interface{}, error)


查看完整回答
反對 回復 2022-08-30
  • 2 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號