当前位置: 代码网 > it编程>前端脚本>Golang > go解析YAML文件(多文档解析)

go解析YAML文件(多文档解析)

2024年11月26日 Golang 我要评论
概述摘要: 在kubernetes二次开发中,常用yaml文件来创建资源,比如pod,deployment。在使用client-go创建资源之前,需要将yaml文件转换为资源对象obj。本文介绍yam

概述

摘要: 在kubernetes二次开发中,常用yaml文件来创建资源,比如pod,deployment。在使用client-go创建资源之前,需要将yaml文件转换为资源对象obj。本文介绍yaml文件的编码和解码的使用。

正文

yaml文档介绍

yaml 是一种轻量级的数据序列化格式,用于在不同平台间传输数据,也用于配置文件等场景。在 yaml 中,整个数据文件称为“文档”,而一般情况下,每个 yaml 文件只包含一个文档。而在kubernetes使用中,kubectl为了创建资源方便性,常用的yaml文件确包括多个文档。
文档可以包含一个或多个“节点”,每个节点包含一个或多个键值对。键值对之间的关系使用冒号(:)表示,键值对的键和值之间使用空格隔开,同时整个键、值对的行末不能有多余的空格。一个节点可以用减号(-)开头表示它是一个序列,即列表。

# 这是一个 yaml 文档
name:  tom
age: 30
hobbies: 
  - reading
  - running
  - swimming

在这个文档中,使用“#”符号表示注释,每个节点的键和值之间用冒号分隔,节点之间使用换行符分隔。在“hobbies”节点中,使用“-”符号表示这是一个序列(即一个列表),列表中的项目用“-”符号开始表示

yaml 文档特点包括

  • 易读性:yaml 使用缩进和结构化的格式,使得它非常易读。它使用空格而不是特殊符号来表示层级关系,使得文档具有良好的可读性。

  • 简洁性:yaml 使用简洁的语法来表示数据结构,避免了冗余和重复。它支持使用引用和折叠块等特性来简化文档的编写。

  • 可嵌套性:yaml 支持嵌套结构,可以在一个节点中包含其他节点,从而表示更复杂的数据结构。这种嵌套结构使得数据的组织更加灵活和清晰。

  • 跨平台:yaml 是一种与编程语言无关的数据格式,可以轻松地在不同的编程语言和平台之间进行交换和共享。

  • 强大的数据表达能力:yaml 支持表示各种数据类型,包括字符串、整数、浮点数、布尔值、日期、时间、正则表达式等。它还支持列表、哈希表等数据结构。

  • 注释:yaml 允许在文档中包含注释,注释以“#”符号开头,可以用于提供有关数据的额外说明或注解。

  • 可扩展性:yaml 允许用户通过自定义标签和类型的方式扩展其功能,使其适应更多的应用场景和需求。

  • 与配置文件的兼容性:由于其易读性和简洁性,yaml 在配置文件方面非常流行。它被广泛用于各种软件和框架的配置文件中,如 kubernetesdocker composeansible 等。

    总的来说,yaml 是一种简单、可读性强且功能丰富的数据序列化格式,非常适合在配置文件和数据交换方面使用

对yaml文档的处理常用三方库 "gopkg.in/yaml.v2"

常用方法包括

  • yaml.marshal() 将结构体对象 转换为yaml字符串

  • yaml.unmarshal() 将yaml字符串转换为结构体对象

代码示例

yaml文件与结构体之间的转换

创建一个用于测试yaml文件fakepersonstruct.yaml

---
name: xianwei
age: 18
city: shenzhen

编写测试代码

// go test -run="^testpersonstruct$"  -v
func testpersonstruct(t *testing.t) {
  // 定义一个结构体
	type person struct {
		name string `yaml:"name"`
		age  int    `yaml:"int"`
		city string `yaml:"city"`
	}
	bytestream, err := ioutil.readfile("yamldir/fakepersonstruct.yaml")
	if err != nil {
		t.errorf("cann not open file.err=%v\n", err)
		return
	}

	// yaml字符串转换为person对象
	p := new(person)
	if err := yaml.unmarshal(bytestream, p); err != nil {
		t.errorf("yaml.unmarshal.err=%v\n", err)
		return
	}
	fmt.printf("person= %+v\n", p)

	// person对象转换为yaml字符串
	yamlstr, err := yaml.marshal(p)
	if err != nil {
		t.errorf("yaml.marshal.err=%v\n", err)
		return
	}
	fmt.printf("yamlstr= %+v\n", string(yamlstr))
}

上面代码实现了:

  • yaml字符串转换为person对象
  • person对象转换为yaml字符串

代码输出

=== run   testpersonstruct
person= &{name:xianwei age:0 city:shenzhen}
yamlstr= name: xianwei
int: 0
city: shenzhen

--- pass: testpersonstruct (0.00s)
pass

解析yaml文件并创建pod

使用yaml创建pod时,需要注意的是,需要先将yaml串转换为json串,再由json串unmarshal成一个pod对象。原因是v1.pod类型定义中(源码如下所示),只指定定义字符串的转换。

type pod struct {
	metav1.typemeta `json:",inline"`
	metav1.objectmeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
	spec podspec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
	status podstatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

创建一个用于测试yaml文件pod-nginx.yaml

---
apiversion: v1
kind: pod
metadata:
  name: mynginx
spec:
  containers:
    - name: nginx
      image: nginx:1.14.2

编写测试代码

// go test -run="^testyamlfilepod$"  -v
func testyamlfilepod(t *testing.t) {
	// 将yaml文件转换为pod对象
	bytestream, err := ioutil.readfile("yamldir/pod-nginx.yaml")
	if err != nil {
		t.errorf("cann not open file.err=%v\n", err)
		return
	}

	// yaml串转换为json串
	pod := new(v1.pod)
	// yaml2 表示 三方库"k8s.io/apimachinery/pkg/util/yaml"
	jsonstr, err := yaml2.tojson(bytestream)
	if err != nil {
		t.errorf("yaml2.tojson.err=%v\n", err)
		return
	}
	fmt.printf("jsonstr= %v\n", string(jsonstr))

	// json串转换为pod结构体
	err = json.unmarshal(jsonstr, &pod)
	if err != nil {
		t.errorf("json.unmarshal.err=%v\n", err)
		return
	}
	fmt.printf("pod= %v\n", pod)

	// clientset获取
	restconfig, err := clientcmd.buildconfigfromflags("", "/users/80280051/.kube/dg11test/config")
	if err != nil {
		panic(err)
	}
	k8sclientset, err := kubernetes.newforconfig(restconfig)
	if err != nil {
		panic(err)
	}

	// 创建pod
	_, err = k8sclientset.corev1().pods("default").create(pod)
	if err != nil {
		t.errorf("cann not create pod.err=%v\n", err)
		return
	}
	
}

上面代码实现了:

  • yaml字符串转换为json字符串
  • 再由json字符串转换pod对象
  • 最后使用clientset创建pod

代码输出

=== run   testyamlfilepod
jsonstr= {"apiversion":"v1","kind":"pod","metadata":{"name":"mynginx"},"spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx"}]}}
pod= &pod{objectmeta:{mynginx      0 0001-01-01 00:00:00 +0000 utc <nil> <nil> map[] map[] [] []  []},spec:podspec{volumes:[]volume{},containers:[]container{container{name:nginx,image:nginx:1.14.2,command:[],args:[],workingdir:,ports:[]containerport{},env:[]envvar{},resources:resourcerequirements{limits:resourcelist{},requests:resourcelist{},},volumemounts:[]volumemount{},livenessprobe:nil,readinessprobe:nil,lifecycle:nil,terminationmessagepath:,imagepullpolicy:,securitycontext:nil,stdin:false,stdinonce:false,tty:false,envfrom:[]envfromsource{},terminationmessagepolicy:,volumedevices:[]volumedevice{},startupprobe:nil,},},restartpolicy:,terminationgraceperiodseconds:nil,activedeadlineseconds:nil,dnspolicy:,nodeselector:map[string]string{},serviceaccountname:,deprecatedserviceaccount:,nodename:,hostnetwork:false,hostpid:false,hostipc:false,securitycontext:nil,imagepullsecrets:[]localobjectreference{},hostname:,subdomain:,affinity:nil,schedulername:,initcontainers:[]container{},automountserviceaccounttoken:nil,tolerations:[]toleration{},hostaliases:[]hostalias{},priorityclassname:,priority:nil,dnsconfig:nil,shareprocessnamespace:nil,readinessgates:[]podreadinessgate{},runtimeclassname:nil,enableservicelinks:nil,preemptionpolicy:nil,overhead:resourcelist{},topologyspreadconstraints:[]topologyspreadconstraint{},ephemeralcontainers:[]ephemeralcontainer{},},status:podstatus{phase:,conditions:[]podcondition{},message:,reason:,hostip:,podip:,starttime:<nil>,containerstatuses:[]containerstatus{},qosclass:,initcontainerstatuses:[]containerstatus{},nominatednodename:,podips:[]podip{},ephemeralcontainerstatuses:[]containerstatus{},},}
--- pass: testyamlfilepod (0.05s)
pass

yaml文件中多文档的处理

在使用kubectl或client-go创建pod时,经常会将多个yaml文档写到一个yaml文件。此种情况下,可以通过按字符串"\n—"进行分割,分别处理。

创建一个用于测试yaml文件pod-nginx-secret.yaml

---
apiversion: v1
kind: pod
metadata:
  name: mynginx
spec:
  containers:
    - name: nginx
      image: nginx:1.14.2
---
apiversion: v1
type: opaque
stringdata:
  userdata: "eglhbndlatexmqo="
kind: secret
metadata:
  name: mysecret

编写测试代码

// go test -run="^testyamlfilemultidocument" -mod=vendor -v
func testyamlfilemultidocument(t *testing.t) {
	// 将yaml文件转换为yaml串
	fp, err := ioutil.readfile("yamldir/pod-nginx-secret.yaml")
	if err != nil {
		t.errorf("cann not open file.err=%v\n", err)
		return
	}
	// 定义分隔符
	const yamlseparator = "\n---"

	pod := new(v1.pod)
	secret := new(v1.secret)
	yamlsplit := strings.split(string(fp), yamlseparator)
	fmt.println("len of yamlsplit = ", len(yamlsplit))
	for index, yamlobj := range yamlsplit {
		// 处理第一个yaml文档,转换为 pod 对象
		if index == 0 {
			// 转换为对象
			fmt.println("obj=", yamlobj)
			if err = yaml.unmarshal([]byte(yamlobj), pod); err != nil {
				t.errorf("yaml unmarshal error of pod.err = %v\n", err)
				return
			}
			fmt.printf("pod obj =%+v\n", pod)
		}
		// 处理第二个yaml文档,转换为secret对象
		if index == 1 {
			fmt.println("obj=", yamlobj)
			// 转换为对象
			if err = yaml.unmarshal([]byte(yamlobj), secret); err != nil {
				t.errorf("yaml unmarshal error of secret.err = %v\n", err)
				return
			}
			fmt.printf("secret obj =%+v\n", secret)
		}

	}

}

上面代码实现了:

  • 对yaml字符串按"\n—"进行分割
  • 对分割后的第一个yaml文档,转换为 pod 对象
  • 对分割后的第二个yaml文档,转换为secret对象

代码输出

=== run   testyamlfilemultidocument
len of yamlsplit =  2
obj= ---
apiversion: v1
kind: pod
metadata:
  name: mynginx
spec:
  containers:
    - name: nginx
      image: nginx:1.14.2
pod obj =&pod{objectmeta:{      0 0001-01-01 00:00:00 +0000 utc <nil> <nil> map[] map[] [] []  []},spec:podspec{volumes:[]volume{},containers:[]container{container{name:nginx,image:nginx:1.14.2,command:[],args:[],workingdir:,ports:[]containerport{},env:[]envvar{},resources:resourcerequirements{limits:resourcelist{},requests:resourcelist{},},volumemounts:[]volumemount{},livenessprobe:nil,readinessprobe:nil,lifecycle:nil,terminationmessagepath:,imagepullpolicy:,securitycontext:nil,stdin:false,stdinonce:false,tty:false,envfrom:[]envfromsource{},terminationmessagepolicy:,volumedevices:[]volumedevice{},startupprobe:nil,},},restartpolicy:,terminationgraceperiodseconds:nil,activedeadlineseconds:nil,dnspolicy:,nodeselector:map[string]string{},serviceaccountname:,deprecatedserviceaccount:,nodename:,hostnetwork:false,hostpid:false,hostipc:false,securitycontext:nil,imagepullsecrets:[]localobjectreference{},hostname:,subdomain:,affinity:nil,schedulername:,initcontainers:[]container{},automountserviceaccounttoken:nil,tolerations:[]toleration{},hostaliases:[]hostalias{},priorityclassname:,priority:nil,dnsconfig:nil,shareprocessnamespace:nil,readinessgates:[]podreadinessgate{},runtimeclassname:nil,enableservicelinks:nil,preemptionpolicy:nil,overhead:resourcelist{},topologyspreadconstraints:[]topologyspreadconstraint{},ephemeralcontainers:[]ephemeralcontainer{},},status:podstatus{phase:,conditions:[]podcondition{},message:,reason:,hostip:,podip:,starttime:<nil>,containerstatuses:[]containerstatus{},qosclass:,initcontainerstatuses:[]containerstatus{},nominatednodename:,podips:[]podip{},ephemeralcontainerstatuses:[]containerstatus{},},}
obj= 
apiversion: v1
type: opaque
stringdata:
  userdata: "eglhbndlatexmqo="
kind: secret
metadata:
  name: mysecret
secret obj =&secret{objectmeta:{      0 0001-01-01 00:00:00 +0000 utc <nil> <nil> map[] map[] [] []  []},data:map[string][]byte{},type:opaque,stringdata:map[string]string{},}
--- pass: testyamlfilemultidocument (0.00s)
pass

总结

本文介绍了yaml文档的特点,并用代码演示了go语言对yaml文档的处理,特别是描述了当yaml文件中存在多个yaml文档时如何处理的方法。

到此这篇关于go解析yaml文件(多文档解析)的文章就介绍到这了,更多相关go解析yaml文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com