当前位置:网站首页>Golang — 解析 yaml 文件
Golang — 解析 yaml 文件
2022-07-26 22:49:00 【itsgopher】
Golang — 解析 yaml 文件
yaml 文件是研发人员最常用的配置文件,yaml 文件的树形结构一直很受大家的欢迎。有过 SpringBoot 开发经验的同学对 yaml 非常熟悉,SpringBoot 整个项目的运行就需要一个 application.yaml 文件的支持,那么 Golang 项目中的 yaml 文件是如何解析的呢?Let`s dive in!
PS:根据 godocs 的说法,Golang 有三个强大的工具包支持 yaml 文件的解析,分别是:go-gypsygo-yamlgoccy-yaml。本文中我们将讨论其中 go-yaml 的用法。
对 yaml 解析源码感兴趣的同学请进入:go-yaml源码链接
Simple Demo
第一步,我们创建好项目后导入 go-yaml 依赖:
* go-yaml go get gopkg.in/yaml.v3
go: added gopkg.in/yaml.v3 v3.0.1
第二步,创建 main 文件并在内部编写一个简单的结构体:
type ConfDemo struct {
// 后面的 yaml 注解是在 yaml 文件中的属性名
A int `yaml:"a"`
B string `yaml:"b"`
C bool `yaml:"c"`
D []string `yaml:"d"`
E struct {
EA string `yaml:"ea"`
EB string `yaml:"eb"`
} `yaml:"e"`
}
第三步,在主目录下创建 conf 目录,并在 conf 目录下创建 conf_demo.yaml 文件去编写我们的配置:
a: 1
b: "I am B"
c: true
d:
- "I"
- "am"
- "D"
e:
ea: "I am EA"
eb: "I am EB"
第四步,编写 main 函数:
func main() {
// 读取文件所有内容装到 []byte 中
bytes, err := ioutil.ReadFile("config/conf_demo.yaml")
if err != nil {
log.Fatalln(err)
}
// 创建配置文件的结构体
var confDemo ConfDemo
// 调用 Unmarshall 去解码文件内容
// 注意要穿配置结构体的指针进去
err = yaml.Unmarshal(bytes, &confDemo)
if err != nil {
log.Fatalln(err)
}
// 调用 Unmarshall 对解码出来的 confDemo 进行编码
// 返回的 yml 是 []byte 类型的
yml, err := yaml.Marshal(confDemo)
if err != nil {
log.Fatalln(err)
}
// 输出结果
fmt.Printf("%#v\n", confDemo)
fmt.Printf("%s\n", yml)
}
第五步,运行并查看结果:
* go-yaml go run main.go
main.ConfDemo{
A:1, B:"I am B", C:true, D:[]string{
"I", "am", "D"}, E:struct {
EA string "yaml:\"ea\""; EB string "yaml:\"eb\"" }{
EA:"I am EA", EB:"I am EB"}}
a: 1
b: I am B
c: true
d:
- I
- am
- D
e:
ea: I am EA
eb: I am EB
go-yaml 其他解析方法
第一种解析方法即 simple Demo 中展现的 Marshall 和 Unmarshall 方法,他们会直接在结构体和字节流上进行操作。但有时我们为了图方便想把读取字节流这一步也交给组件去执行,这时候我们可以利用 yaml.Encoder 和 yaml.Decoder。
yaml.Encoder 和 yaml.Decoder 在 io.Writer 和 io.Reader 上进行操作读取其字节流并执行编码和解码的动作。我们将上面的例子以这种方法再次实现一遍:
func main() {
// 利用 os.Open 获取 File 对象,该对象实现了 io.Reader 和 io.Writer
file, err := os.Open("config/conf_demo.yaml")
if err != nil {
log.Fatalln(err)
}
// 构造新的 Decoder,并传入 file
decoder := yaml.NewDecoder(file)
// 配置文件结构体
var confDemo ConfDemo
// 解码操作,注意要传入地址
err = decoder.Decode(&confDemo)
// 输出解码结果
fmt.Printf("%#v\n", confDemo)
if err != nil {
log.Fatalln(err)
}
// 构造新的 Encoder,这里直接传入了 os.Stdout,代表结果直接输出到控制台
encoder := yaml.NewEncoder(os.Stdout)
// 编码并输出
err = encoder.Encode(confDemo)
if err != nil {
log.Fatalln(err)
}
}
运行结果:
* go-yaml go run main.go
main.ConfDemo{
A:1, B:"I am B", C:true, D:[]string{
"I", "am", "D"}, E:struct {
EA string "yaml:\"ea\""; EB string "yaml:\"eb\"" }{
EA:"I am EA", EB:"I am EB"}}
a: 1
b: I am B
c: true
d:
- I
- am
- D
e:
ea: I am EA
eb: I am EB
边栏推荐
- Autojs learning - realize image cutting
- Text to image paper intensive reading rat-gan: recursive affine transformation for text to image synthesis
- 2022zui新抖音24小时循环值守直播监控(一)直播间开播监控
- Flink1.13.6 detailed deployment method
- Static routing default routing VLAN experiment
- Difference between fat AP and thin AP & advantages and disadvantages of networking
- 测开基础 日常刷题 (持续更新ing...)
- OSPF在MGRE环境下配置及LSA的优化---减少LSA更新量(汇总、特殊区域)
- Unity Huatuo hot update environment installation and sample project
- 第三讲--GPIO输入输出库函数使用以及相关例程
猜你喜欢

动态路由rip协议实验

OSPF在MGRE环境下配置及LSA的优化---减少LSA更新量(汇总、特殊区域)

NAT network address translation experiment

HCIA静态路由综合实验
![[FPGA tutorial case 28] one of DDS direct digital frequency synthesizers based on FPGA -- principle introduction](/img/bf/ce4bc33d2a0fc7fe57105e20fbafcf.png)
[FPGA tutorial case 28] one of DDS direct digital frequency synthesizers based on FPGA -- principle introduction
![[详解C语言]一文带你认识C语言,让你醍醐灌顶](/img/37/205c1c6eb2ba704941e48ff89c6268.png)
[详解C语言]一文带你认识C语言,让你醍醐灌顶

7.13 蔚来提前批笔试

解决方案:炼丹师养成计划 Pytorch+DeepLearning遇见的各种报错与踩坑避坑记录(二)

解决方案:炼丹师养成计划 Pytorch+DeepLearning遇见的各种报错与踩坑避坑记录(三)

Text to image intensive reading of paper gr-gan: gradually refine text to image generation
随机推荐
【mysql】mysql启动关闭命令以及一些报错解决问题
[explain C language in detail] takes you to play with functions
通过对射式红外传感器计次实验讲解EXTI中断
Beyond hidden display ellipsis
【volatile原理】volatile原理
OSPF static experiment
[FPGA tutorial case 30] DDS direct digital frequency synthesizer based on FPGA -- frequency accuracy analysis with MATLAB
Static comprehensive experiment (comprehensive exercise of static route, loopback interface, default route, empty interface, floating static)
6.29 Zhong'an Summer Internship
2022年T2I文本生成图像 中文期刊论文速览-1(ECAGAN:基于通道注意力机制的文本生成图像方法+CAE-GAN:基于Transformer交叉注意力的文本生成图像技术)
TCP的三次握手与四次断开
【数据库课程设计】SQLServer数据库课程设计(学生宿舍管理),课设报告+源码+数据库关系图
STM32 HAL库串口(UART/USART)调试经验(一)——串口通信基础知识+HAL库代码理解
ACM mode input and output exercise
动态路由ofps协议配置
解决方案:炼丹师养成计划 Pytorch+DeepLearning遇见的各种报错与踩坑避坑记录(三)
7.13 蔚来提前批笔试
FID index reproduction step on the pit to avoid the pit text generation image FID quantitative experiment whole process reproduction (FR é Chet inception distance) quantitative evaluation experiment s
Es specify user name and password when instantiating resthighlevelclient
Vitgan: training Gans with vision transformers