【每天一個(gè)Go知識(shí)點(diǎn)】(14)【轉(zhuǎn)】golang 配置文件操作(viper 庫操作)

一:簡要介紹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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容