解析带有“---”的yaml文件

Parse yaml files with "---" in it

我正在使用 https://github.com/go-yaml/yaml 来解析 yaml 文件:

type TestConfig struct {
   Test string `yaml:"test"`
}


yaml 文件:

test: 123

---

test: 456

但是 yaml.Unmarshal() 只解析了第一段,我该如何解析其余部分?

But yaml.Unmarshal() only parses the first segment, how can I parse the rest of it?

yaml.Unmarshal's doc 说(强调我的):

Unmarshal decodes the first document found within the in byte slice and assigns decoded values into the out value.

如果您想解码 系列 文档,请对数据流调用 yaml.NewDecoder(),然后多次调用解码器的 .Decode(...)。使用 io.EOF 来标识记录的结尾。

我通常使用无限 for 循环和 break 条件:

decoder := yaml.NewDecoder(bytes.NewBufferString(data))
for {
    var d Doc
    if err := decoder.Decode(&d); err != nil {
        if err == io.EOF {
            break
        }
        panic(fmt.Errorf("Document decode failed: %w", err))
    }
    fmt.Printf("%+v\n", d)
}
fmt.Printf("All documents decoded")

(https://go.dev/play/p/01xdzDN0qB7)