如何将多行字符串编组为Yaml值

时间:2018-07-04 09:51:07

标签: parsing go yaml multilinestring

我有一个结构

type Products struct {
    Name    string
    Version string
    Description     string
}

将多行字符串常量作为Description字段的值,该常量如下

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`

然后我使用包gopkg.in/yaml.v2整理上述结构(该结构包含以上常量作为其字段的值),如下所示:

data, err = yaml.Marshal(updateDescriptorV3)

,然后使用yaml将生成的os.file.Write()内容写入文件 但是在上面生成的yaml文件中,另外一个-位于literal_block符号(|之后),我在做什么错了?

  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

要在yaml中按如下方式获取上述常量作为literal_block,需要做什么?

  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

1 个答案:

答案 0 :(得分:0)

它正常工作。您的多行字符串不会以换行符结尾,因此YAML必须在解析换行符时将其删除。这正是rv的作用。

如果您确实想要|-,只需在输入字符串的末尾添加换行符,但要注意功能上的区别。

有关在YAML中包括多行字符串的各种方式的完整说明,请参见this answer