golang如何通過viper讀取config.yaml文件
1.導入依賴包
import ( ? ? "github.com/spf13/viper" )
2.編寫yaml文件
放在conf目錄下,文件名叫config.yaml
# TODO ?本地調(diào)試時放開 KubeSphere_URL: http://192.168.103.48:3188 # TODO 部署到環(huán)境時放開 #KubeSphere_URL: http://ks-apiserver.kubesphere-system.svc:80 KubesphereAdminUser: admin KubespherePassword: Admin123 #TODO 調(diào)用梅姐服務的ip,暫用當前,后續(xù)需要修改 Other_service_IP: http://192.168.103.48:30412 #Other_service_IP: http://container-cloud-system-controller-manager-metrics-service.container-cloud-system-system.svc:8093 Other_service_URL: /capis/quota.ictnj.io/v1alpha1/namespaces/ #TODO harbor鏡像倉庫地址 HARBOR_URL: https://192.168.66.4:443 HARBOR_ADMIN_USERNAME: admin HARBOR_ADMIN_PASSWD: Harbor12345 HARBOR_IP_HTTPS: 192.168.66.4:443 HARBOR_SSH_ADDRESS: 192.168.103.48:53304 HARBOR_SSH_USERNAME: root HARBOR_SSH_PASSWD: peng123.
3.編寫讀取yaml文件的go文件
放在config目錄下,文件名叫config.go
需要注意的是目錄的問題,如果放在同目錄,直接用configurationPath,不同的編輯器,
vscode跟golang對相對路徑處理不同

package config
import (
? ? "github.com/spf13/viper"
)
const (
? ? configurationName = "config"
? ? configurationPath = "./conf"
? ? // vscode特殊讀取路徑
? // ?configurationPath_vscode = "../conf"?
)
var Config *viper.Viper
func init() {
? ? Config = viper.New()
? ? Config.SetConfigName(configurationName)
? ? Config.AddConfigPath(configurationPath)
? ? Config.SetConfigType("yaml")
? ? Config.AddConfigPath(configurationPath)
? ? if err := config.ReadInConfig(); err != nil {
? ? ?panic(err)
? ?}?
}如果config.yaml跟config.go放在同目錄簡單的路徑用上面這個,如果路徑不同,且不同的同事用不同的編譯軟件,可以嘗試下面的路徑兼容
package config
import (
? ? "github.com/spf13/viper"
)
const (
? ? configurationName = "config"
? ? configurationPath = "./conf"
? ? // vscode特殊讀取路徑
? ? configurationPath_vscode = "../conf"?
)
var Config *viper.Viper
func init() {
? ? Config = viper.New()
? ? Config.SetConfigName(configurationName)
? ? Config.AddConfigPath(configurationPath)
? ? Config.SetConfigType("yaml")
? ? if err := Config.ReadInConfig(); err != nil {
? ? ? ? Config.AddConfigPath(configurationPath_vscode)
? ? ? ? if err := Config.ReadInConfig(); err != nil {
? ? ? ? ? ? Config.AddConfigPath(configurationPath)
? ? ? ? ? ? panic(err)
? ? ? ? }
? ? }
}4.使用config對象

Config.GetString("KubeSphere_URL")5.viper源碼分析
type Viper struct {
? ? // Delimiter that separates a list of keys
? ? // used to access a nested value in one go
? ? keyDelim string
? ? // A set of paths to look for the config file in
? ? configPaths []string
? ? // The filesystem to read config from.
? ? fs afero.Fs
? ? // A set of remote providers to search for the configuration
? ? remoteProviders []*defaultRemoteProvider
? ? // Name of file to look for inside the path
? ? configName ? ? ? ?string
? ? configFile ? ? ? ?string
? ? configType ? ? ? ?string
? ? configPermissions os.FileMode
? ? envPrefix ? ? ? ? string
? ? automaticEnvApplied bool
? ? envKeyReplacer ? ? ?StringReplacer
? ? allowEmptyEnv ? ? ? bool
? ? config ? ? ? ? map[string]interface{}
? ? override ? ? ? map[string]interface{}
? ? defaults ? ? ? map[string]interface{}
? ? kvstore ? ? ? ?map[string]interface{}
? ? pflags ? ? ? ? map[string]FlagValue
? ? env ? ? ? ? ? ?map[string]string
? ? aliases ? ? ? ?map[string]string
? ? typeByDefValue bool
? ? // Store read properties on the object so that we can write back in order with comments.
? ? // This will only be used if the configuration read is a properties file.
? ? properties *properties.Properties
? ? onConfigChange func(fsnotify.Event)
}func (v *Viper) ReadInConfig() error {
? ? jww.INFO.Println("Attempting to read in config file")
? ? filename, err := v.getConfigFile()
? ? if err != nil {
? ? ? ? return err
? ? }
? ? if !stringInSlice(v.getConfigType(), SupportedExts) {
? ? ? ? return UnsupportedConfigError(v.getConfigType())
? ? }
? ? jww.DEBUG.Println("Reading file: ", filename)
? ? file, err := afero.ReadFile(v.fs, filename)
? ? if err != nil {
? ? ? ? return err
? ? }
? ? config := make(map[string]interface{})
? ? err = v.unmarshalReader(bytes.NewReader(file), config)
? ? if err != nil {
? ? ? ? return err
? ? }
? ? v.config = config
? ? return nil
}
把yaml文件的鍵值讀取到viper對象的config當中
到此這篇關于golang如何通過viper讀取config.yaml文件的文章就介紹到這了,更多相關golang讀取config.yaml內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
golang實現(xiàn)http服務器處理靜態(tài)文件示例
這篇文章主要介紹了golang實現(xiàn)http服務器處理靜態(tài)文件的方法,涉及Go語言基于http協(xié)議處理文件的相關技巧,需要的朋友可以參考下2016-07-07
go并發(fā)編程sync.Cond使用場景及實現(xiàn)原理
這篇文章主要為大家介紹了go并發(fā)編程sync.Cond使用場景及實現(xiàn)原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
Golang實現(xiàn)WebSocket服務的項目實踐
本文介紹如何使用Golang實現(xiàn)實時后端WebSocket服務,首先使用Gin框架搭建http服務,然后使用gorilla/websocket庫實現(xiàn)簡單后端WebSocket服務,具有一定的參考價值,感興趣的可以了解一下2023-05-05

