Golang實踐筆錄之讀取yaml配置文件
本文對 yaml 文件進行解析。
下載
yaml執(zhí)行 go get github.com/spf13/viper 安裝。
golang 有很多庫可以解釋 yaml 文件。本文選用 viper 進行解析,執(zhí)行 go get github.com/spf13/viper 安裝。
yaml語法規(guī)則
- yaml對大小寫敏感。
- yaml的層級關(guān)系只能使用空格縮進,同一層縮進的空格數(shù)量相同即可,數(shù)量不重要。不允許使用tab鍵。
- 使用
#進行注釋,與shell一樣。
數(shù)據(jù)類型
YAML 支持以下常用幾種數(shù)據(jù)類型:
- 對象:鍵值對的集合,又稱為映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 數(shù)組:一組按次序排列的值,又稱為序列(sequence) / 列表(list)
- 純量(scalars):單個的、不可再分的值
測試
yaml 配置文件
# yaml測試樣例
# null 或 NULL 為關(guān)鍵字,不能寫
# 表示 bool 真假的幾個值
result_true:
- y
- Y
- yes
- Yes
- YES
- true
- True
- TRUE
- on
- On
- ON
# 數(shù)組的另一種形式
result_false: [n, N, no, No, NO , false, False, FALSE , off, Off, OFF]
# 名稱
# 字符串
name: conf file
# 版本
# 如按浮點,2.0會轉(zhuǎn)換成2
# 如按字符串,保留原樣
version: 2.0
# 布爾類,轉(zhuǎn)換為1或0
need: true
# 時間
time: 2020-10-03T09:21:13
empty: nul
# 對象
# 加雙引號會轉(zhuǎn)義\n,即會換行
my:
name: late \n lee
name1: "late \n lee"
age: 99
# 塊
text: |
hello
world!
# 數(shù)組
fruit:
- apple
- apple1
- apple2
- apple3
- apple4
- apple5
# 多級數(shù)組
multi:
sta:
- 110 210 ddd 99
- 133 135 1 2 1588 1509
- 310-410
- 333-444
# 多層級
loginfo:
log:
dir: log
# 多級對象
mymap:
dir: "mymap"
map_data:
- name: "在線"
attri: "在線電子"
url: "http://abc.com"
- name: "離線"
attri: "離線電子"
url: "http://ccc.com"
# more
該示例基本涵蓋了大部分的 yaml 格式。包括:字符串,數(shù)值、數(shù)組、多級map。
測試代碼
測試代碼如下:
package test
import (
"fmt"
"os"
"testing"
"github.com/spf13/viper"
)
var (
cfgFile string
)
type mapUrl_t struct {
Name string `json:"name"`
Attri string `json:"attri"`
Url string `json:"url"`
}
func TestYaml(t *testing.T) {
fmt.Println("test of yaml...")
// 設(shè)置配置文件的2種方式
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\nversion: %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)
// 字符串數(shù)組
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)
// 讀取不存在的字段,字符串為空,數(shù)值為0
bad := viper.GetString("bad")
bad1 := viper.GetInt("my.bad")
fmt.Printf("bad: [%v] bad1: [%v]\n", bad, bad1)
// 按數(shù)值、字符串讀取on、off等值
result := viper.GetIntSlice("result_true")
fmt.Printf("result true: [%v]\n", result)
result1 := viper.GetStringSlice("result_true")
fmt.Printf("result1 true: [%v]\n", result1)
result = viper.GetIntSlice("result_false")
fmt.Printf("result false: [%v]\n", result)
result1 = viper.GetStringSlice("result_false")
fmt.Printf("result1 false: [%v]\n", result1)
logdir := viper.GetString("loginfo.log.dir")
fmt.Printf("logdir: %v\n", logdir)
// 多級對象
// tmpMap := make([]mapUrl_t, 0, 20)
var tmpMap []mapUrl_t
viper.UnmarshalKey("mymap.map_data", &tmpMap)
for _, item := range tmpMap {
fmt.Printf("name: %v url: %v\n", item.Name, item.Url)
}
}
測試命令:
go test -v -run TestYaml
測試結(jié)果:
test of yaml... 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: [0] result true: [[1 1 1 1 1 1 1 1 1 1 1]] result1 true: [[true true true true true true true true true true true]] result false: [[0 0 0 0 0 0 0 0 0 0 0]] result1 false: [[false false false false false false false false false false false]] logdir: log name: 在線 url: http://abc.com name: 離線 url: http://ccc.com
結(jié)果說明
1、name: "late \n lee" 輸出會換行。而 name: late \n lee 則會原樣輸出。
2、參數(shù)的值不能為 null 或 NULL,但可以為nul。如果為 null,解析的值為空。
3、如果字段不存在,不會報錯,按字符串解析得到的值為空,如用數(shù)值,值為0。
4、表示false的關(guān)鍵字有n, N, no, No, NO , false, False, FALSE , off, Off, OFF, 表示true的有y, Y, yes, Yes, YES, true, True, TRUE, on, On, ON。在使用時需要注意。
5、對于多層級的對象,可以用viper.UnmarshalKey,用法與解析json類似。
總結(jié)
到此這篇關(guān)于Golang實踐筆錄之讀取yaml配置文件的文章就介紹到這了,更多相關(guān)Go讀取yaml配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go語言yaml轉(zhuǎn)map、map遍歷的實現(xiàn)
本文主要介紹了go語言yaml轉(zhuǎn)map、map遍歷的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
golang如何用type-switch判斷interface變量的實際存儲類型
這篇文章主要介紹了golang如何用type-switch判斷interface變量的實際存儲類型,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Golang中類型轉(zhuǎn)換利器cast庫的用法詳解
cast庫是一個簡潔而強大的第三方庫,它的主要功能是實現(xiàn)類型之間的安全轉(zhuǎn)換,而在Golang開發(fā)中,類型轉(zhuǎn)換是一個常見且不可避免的過程,下面我們就來看看cast庫在Golang中的具體應(yīng)用吧2024-11-11
Windows下在CMD下執(zhí)行Go出現(xiàn)中文亂碼的解決方法
在cmd下運行g(shù)o程序或者是GOLAND的Terminal下運行g(shù)o程序會出現(xiàn)中文亂碼的情況。本文就詳細的介紹下解決方法,具有一定的參考價值,感興趣的可以了解一下2021-12-12

