环境搭建
创建D:/zdpgo目录,将zdpgo_yaml解压到这个目录。
创建D:/zdpgo/demo目录。
初始化模块:
go mod init demo
使用vscode打开。
code .
修改 go.mod
module demo
go 1.22
require zdpgo_yaml v0.1.0
replace zdpgo_yaml v0.1.0 => ../zdpgo_yaml
写入yaml文件
编写一个Go程序,将以下数据写入到config.yaml文件中。
data := map[string]interface{
} {
"name": "源滚滚编程",
"age": 33,
"email": "[email protected]"
}
期望的输出结果:
name: 源滚滚编程
age: 33
email: [email protected]
示例代码:
package main
import (
"fmt"
"os"
yaml "zdpgo_yaml"
)
func main() {
data := map[string]interface{
}{
"name": "源滚滚编程",
"age": 33,
"email": "[email protected]",
}
// 转换为yaml
yamlData, err := yaml.Marshal(data)
if err != nil {
fmt.Println("转换为yaml失败:", err)
return
}
// 写入文件
err = os.WriteFile("config.yaml", yamlData, 0644)
if err != nil {
fmt.Println("写入yaml文件失败:", err)
return
}
// 成功
fmt.Println("写入yaml文件成功")
}
代码分析:
- 数据准备,使用
map[string]interface{}
这种数据结构准备yaml数据,这种方式简单灵活。 - 序列化,使用
yaml.Marshal
方法将Go语言的数据结构转换为yaml文件格式的字节切片。 - 写入文件,使用
os.WriteFile
将yaml数据写入到文件,0644是文件的全新,表示所有者可读,可写,其他用户可读。 - 错误处理,无论是在转换的时候,还是写入的时候,我们都加入了错误处理的代码,让程序更加的健壮。
写入嵌套的yaml
核心代码:
package main
import (
"fmt"
"os"
yaml "zdpgo_yaml"
)
func main() {
data := map[string]interface{
}{
"server": map[string]interface{
}{
// 服务器配置
"host": "127.0.0.1", // 主机地址
"port": 8080, // 端口号
"timeout": "30s", // 超时时间
},
"database": map[string]interface{
}{
// 数据库配置
"host": "127.0.0.1",
"port": 3306,
"username": "root",
"password": "root",
"database": "zdpgo_yaml",
},
}
// 转换为yaml
yamlData, err := yaml.Marshal(data)
if err != nil {
fmt.Println("转换为yaml格式失败:", err)
return
}
// 写入到文件
err = os.WriteFile("config.yaml", yamlData, 0644)
if err != nil {
fmt.Println("写入到yaml文件失败:", err)
return
}
// 成功
fmt.Println("写入到yaml文件成功!")
}
输出结果:
database:
database: zdpgo_yaml
host: 127.0.0.1
password: root
port: 3306
username: root
server:
host: 127.0.0.1
port: 8080
timeout: 30s
读取yaml文件
假设我们有config.yaml文件如下:
name: 源滚滚编程
age: 33
使用Go语言读取这个yaml配置文件并输出所有的值。
示例代码:
package main
import (
"fmt"
"os"
yaml "zdpgo_yaml"