Golang實(shí)踐筆錄之讀取yaml配置文件
本文對 yaml 文件進(jìn)行解析。
下載
yaml執(zhí)行 go get github.com/spf13/viper 安裝。
golang 有很多庫可以解釋 yaml 文件。本文選用 viper 進(jìn)行解析,執(zhí)行 go get github.com/spf13/viper 安裝。
yaml語法規(guī)則
- yaml對大小寫敏感。
- yaml的層級關(guān)系只能使用空格縮進(jìn),同一層縮進(jìn)的空格數(shù)量相同即可,數(shù)量不重要。不允許使用tab鍵。
- 使用
#進(jìn)行注釋,與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
# 版本
# 如按浮點(diǎn),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)
// 字符串?dāng)?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實(shí)踐筆錄之讀取yaml配置文件的文章就介紹到這了,更多相關(guān)Go讀取yaml配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go語言實(shí)現(xiàn)的memcache協(xié)議服務(wù)的方法
這篇文章主要介紹了go語言實(shí)現(xiàn)的memcache協(xié)議服務(wù)的方法,實(shí)例分析了Go語言使用memcache的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
Go依賴注入DI工具wire使用詳解(golang常用庫包)
依賴注入是指程序運(yùn)行過程中,如果需要調(diào)用另一個對象協(xié)助時,無須在代碼中創(chuàng)建被調(diào)用者,而是依賴于外部的注入,本文結(jié)合示例代碼給大家介紹Go依賴注入DI工具wire使用,感興趣的朋友一起看看吧2022-04-04
Go項(xiàng)目中使用Casbin實(shí)現(xiàn)RBAC權(quán)限管理教程
本文主要介紹了Go項(xiàng)目中使用Casbin實(shí)現(xiàn)RBAC權(quán)限管理教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2026-01-01
Golang實(shí)現(xiàn)簡易的rpc調(diào)用
RPC指(Remote Procedure Call Protocol)遠(yuǎn)程過程調(diào)用協(xié)議。本文將實(shí)現(xiàn)利用Golang進(jìn)行rpc調(diào)用(只實(shí)現(xiàn)一個rpc框架基本的功能,不對性能做保證),需要的可以參考一下2023-03-03
Golang跳轉(zhuǎn)語句continue與goto使用語法詳解
這篇文章主要介紹了Golang跳轉(zhuǎn)語句continue與goto使用語法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01
聊聊go xorm生成mysql的結(jié)構(gòu)體問題
這篇文章主要介紹了go xorm生成mysql的結(jié)構(gòu)體問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2022-03-03

