a11hard
a11hard

Reputation: 2054

How do you marshal a line break in Go 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"`
}

Upvotes: 3

Views: 2242

Answers (2)

germanio
germanio

Reputation: 859

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

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

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)
}

The result looks like this:

$ 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.

Upvotes: 2

aureliar
aureliar

Reputation: 1594

As empty line don't have a meaning in yaml, the default library does not create them, and does not expose an option to do so in the struct field tag.

However, if you want fine grained control of how a type is marshalled in yaml, you can always make it implements yaml.Marshaller by defining a method MarshalYAML() (interface{}, error)

Upvotes: 1

Related Questions