Kasun Siyambalapitiya
Kasun Siyambalapitiya

Reputation: 4403

How to marshal a multiline string to yaml value

I have a struct

type Products struct {
    Name    string
    Version string
    Description     string
}

holding a multiline string constant as the value for Description field, the constant is as follows

const DEFAULT_DESCRIPTION = `Please add the description here without removing the literal block (|)
    Sample description will be as follows,
    Fixes for the following in rabbitmq transport
    (i)   Channel not closing issue in rabbitmq publisher
    (ii)  Performance improvements to the transport by introducing a channel pool (configurable) and parameterising queue and exchange creation.
    (iii) Allow configuring connection factory by name in target url`

Then I use the package gopkg.in/yaml.v2 for marshaling the above struct (which contains the above constant as a value for its field) as follows

data, err = yaml.Marshal(updateDescriptorV3)

and write the generated yaml content to a file using os.file.Write() But in the yaml file generated above an additional - exists after literal_block symbol (|) What I am doing wrong?

  description: |-
Please add the description here without removing the literal block (|)
Sample description will be as follows,
Fixes for the following in rabbitmq transport
(i)   Channel not closing issue in rabbitmq publisher
(ii)  Performance improvements to the transport by introducing a channel pool (configurable) and parameterising queue and exchange creation.
(iii) Allow configuring connection factory by name in target url

What needs to be done to get the above constant as a literal_block in yaml as follows?

  description: |
Please add the description here without removing the literal block (|)
Sample description will be as follows,
Fixes for the following in rabbitmq transport
(i)   Channel not closing issue in rabbitmq publisher
(ii)  Performance improvements to the transport by introducing a channel pool (configurable) and parameterising queue and exchange creation.
(iii) Allow configuring connection factory by name in target url

Upvotes: 4

Views: 5004

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79614

It is working properly. Your multi-line string does not end in a newline, so it is necessary for the YAML to strip the newline when it is parsed. That is precisely what the |- does.

If you really want | instead, just add a newline to the end of your input string, but be aware of the functional difference.

See this answer for a complete explanation of the various ways to include multi-line strings in YAML.

Upvotes: 3

Related Questions