一:簡要介紹Viper
Viper主要是用于處理各種格式的配置文件,簡化程序配置的讀取問題。
- Viper 支持:(后續(xù)會(huì)詳細(xì)介紹)
- 設(shè)置默認(rèn)值
- 從JSON,TOML,YAML,HCL和Java屬性配置文件中讀取
- 實(shí)時(shí)觀看和重新讀取配置文件(可選)
- 從環(huán)境變量中讀取
- 從遠(yuǎn)程配置系統(tǒng)(etcd或Consul)讀取,并觀察變化
- 從命令行標(biāo)志讀取(flag)
- 從緩沖區(qū)讀取
- 設(shè)置顯式值
二:Viper安裝
go get github.com/spf13/viper
三:yaml文件讀取測試
在項(xiàng)目根目錄新建config配置文件目錄,同時(shí)創(chuàng)建一個(gè)yaml格式的配置文件config.yaml,寫入一些測試數(shù)據(jù)
env:
lang: golang
system: mac
author: yanwei
apiTokenKey: Z2luLWNsaTIwMjEwNQ==
apiTokenExpireTime: 1440
apiTokenRebuildTime: 100

// 初始化viper
viper := viper2.New()
// 設(shè)置配置文件名,即上一步提取的
viper.SetConfigName(fileName)
// 設(shè)置配置文件格式
viper.SetConfigType("yaml")
// 設(shè)置配置文件所在目錄,這里固定為config,可以根據(jù)需要更改
viper.AddConfigPath("config")
具體實(shí)現(xiàn)代碼
package main
import (
"fmt"
viper2 "github.com/spf13/viper"
"strings"
)
func Get(fileKey string) interface{} {
index := strings.Index(fileKey, ".")
fileName := fileKey[0:index]
key := fileKey[index+1:]
viper := viper2.New()
viper.SetConfigName(fileName)
viper.SetConfigType("yaml")
viper.AddConfigPath("config")
if err := viper.ReadInConfig(); err != nil {
panic(err.Error())
}
return viper.Get(key)
}
func main(){
fmt.Println(Get("config.env.lang"))
fmt.Println(Get("config.env"))
fmt.Println(Get("config.author"))
}

————————————————
版權(quán)聲明:本文為CSDN博主「棒洗啦」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/douz_lungfish/article/details/118733780