yaml库
import "gopkg.in/yaml.v2"

该库可以很方便的操作yaml文件,这里先展示一下常用的解析方法:

a.yml
a: 10
b: 
	- 1
	- 2
	- 3
intaintb
type YmlObj struct {
	A int
	B []int
}

使用yaml包来解析也很简单,这里我就用go的单元测试来写这个方法了:

func TestGetYamlByUnmarshal(t *testing.T) {
	y := YmlObj{}
	content, err := ioutil.ReadFile("a.yml")
	if err != nil{
		t.Error(err)
	}
	if err = yaml.Unmarshal(content, &y);err != nil{
		t.Error(err)
	}
	fmt.Println(y)
}

/*
OUTPUT:
{10 [1 2 3]}
*/
多文档
------
---
a: 10
b: 
	- 1
	- 2
	- 3
---
a: 20
b: 
	- 4
	- 5
strings.split(str, "---")

可是这样是有问题的,前几天我遇到一份yml文档中包含多个连续的短横线,那结果也可以预见:yml文档被分割成了多个不完整的部分,解析自然也会失败。

实际上yaml这个包对于这种情况是有官方的解决方案的:decode
下面上代码:

func TestGetYaml(t *testing.T) {
	file, err := os.Open("b.yaml")
	if err != nil{
		t.Error(err)
	}
	dec := yaml.NewDecoder(file)
	y := YmlObj{}
	err := dec.Decode(&y)
	for err == nil{
		fmt.Println(y)
		err = dec.Decode(&y)
	}
	if !errors.Is(err, io.EOF){
		t.Error(err)
	}
	fmt.Println("Parse yaml complete!")
}
/*
OUTPUT:
{10 [1 2 3]}
{20 [4 5]}
*/
yaml.NewDecoderdecoderDecodeio.EOFerrorerror