你如何在 Go YAML 中编组换行符? [英] How do you marshal a line break in Go YAML?

查看:40
本文介绍了你如何在 Go YAML 中编组换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a golang CLI I'm programming I collect information on how to configure the tool and I marhsal that as a YAML file. However, I'm not sure how I would add line breaks to make the file more readable?

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"`
}

推荐答案

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

One way to implement this that allows format (and comments) is to use a template engine.

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

Here is a running example that generates a string with the formatted yaml, that can be then saved to a .yml file.

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

No additional libraries are needed and the template is included inside the go file.

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

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

I'm sure there are better ways to implement it, just want to show a quick working example.

这篇关于你如何在 Go YAML 中编组换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆