本文使用 golang 库 viper 对 yaml 文件进行解析。
下载
go get github.com/spf13/viper
测试
yaml 配置文件
# yaml测试样例
# null 或 NULL 为关键字,不能写
# 名称
# 字符串
name: conf file
# 版本
# 如按浮点,2.0会转换成2
# 如按字符串,保留原样
version: 2.0
# 布尔类,转换为1或0
need: true
# 时间
time: 2020-10-03T09:21:13
empty: nul
# 对象
# 加双引号会转义\n,即会换行
my:
name: late \n lee
name1: "late \n lee"
age: 99
# 块
text: |
hello
world!
# 数组
fruit:
- apple
- apple1
- apple2
- apple3
- apple4
- apple5
# 多级数组
multi:
sta:
- 110 210 ddd 99
- 133 135 1 2 1588 1509
- 310-410
- 333-444
该示例基本涵盖了大部分的 yaml 格式。包括:字符串,数值、数组、多级map。
测试代码
测试代码如下:
package main
import (
"fmt"
"os"
"github.com/spf13/viper"
)
var (
cfgFile string
)
func main() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath("./")
viper.SetConfigName("config")
viper.SetConfigType("yaml")
}
viper.AutomaticEnv() // read in environment variables that match
err := viper.ReadInConfig();
if err != nil {
fmt.Println("'config.yaml' file read error:", err)
os.Exit(0)
}
name := viper.GetString("name")
version := viper.GetString("version")
need := viper.GetBool("need")
theTime := viper.GetString("time")
empty := viper.GetString("empty")
text := viper.GetString("text")
fmt.Printf("need: %v name: %v=\n version: %v \ntime: %v \nempty: %s \ntext: %v\n", need, name, version, theTime, empty, text)
name = viper.GetString("my.name")
name1 := viper.GetString("my.name1")
age := viper.GetInt("my.age")
fmt.Printf("name: %v, name1: %v age: %v \n", name, name1, age)
newSta := viper.GetStringSlice("multi.sta")
for idx, value := range newSta {
fmt.Printf("sta[%d]: %v\n", idx, value)
}
fruit := viper.GetStringSlice("fruit")
fmt.Printf("fruit: %v\n", fruit)
bad := viper.GetString("bad")
bad1 := viper.GetString("my.bad")
fmt.Printf("bad: %v bad1: %v\n", bad, bad1)
}
go build
$ ./yaml_test.exe
need: true name: conf file=
version: 2
time: 2020-10-03T09:21:13
empty: nul
text: hello
world!
name: late \n lee, name1: late
lee age: 99
sta[0]: 110 210 ddd 99
sta[1]: 133 135 1 2 1588 1509
sta[2]: 310-410
sta[3]: 333-444
fruit: [apple apple1 apple2 apple3 apple4 apple5]
bad: bad1:
结果说明
name: "late \n lee"name: late \n lee