Go讀取yaml文件到struct類的實(shí)現(xiàn)方法
1、yaml文件準(zhǔn)備
common: secretid: AKIDxxxxx secretKey: 3xgGxxxx egion: ap-guangzhou zone: ap-guangzhou-7 InstanceChargeType: POSTPAID_BY_HOUR
2、config配置類準(zhǔn)備
可以通過在線配置工具轉(zhuǎn)換成struct
例如:https://www.printlove.cn/tools/yaml2go
代碼:
type ConfigData struct { // 公共配置 Common Common `yaml:"common"` } type Common struct { // 密鑰id。密鑰可前往官網(wǎng)控制臺(tái) https://console.cloud.tencent.com/cam/capi 進(jìn)行獲取 SecretId string `yaml:"secretid"` // 密鑰key SecretKey string `yaml:"secretKey"` // 地域 Region string `yaml:"region"` // 可用區(qū) Zone string `yaml:"zone"` //實(shí)例計(jì)費(fèi)模式。取值范圍:PREPAID:預(yù)付費(fèi),即包年包月。POSTPAID_BY_HOUR:按小時(shí)后付費(fèi)。 InstanceChargeType string `yaml:"InstanceChargeType"` }
3、讀取配置文件到配置類
使用viper讀取配置到配置類中
3.1、安裝Viper組件
go install github.com/spf13/viper@latest
3.2、golang** **代碼編寫
yaml文件放在工程根目錄的data文件夾中
package main import ( "bufio" "github.com/spf13/viper" "io" "os" "strings" ) type ConfigData struct { // 公共配置 Common Common `yaml:"common"` } type Common struct { // 密鑰id。 SecretId string `yaml:"secretid"` // 密鑰key SecretKey string `yaml:"secretKey"` // 地域 Region string `yaml:"region"` // 可用區(qū) Zone string `yaml:"zone"` //實(shí)例計(jì)費(fèi)模式。取值范圍:PREPAID:預(yù)付費(fèi),即包年包月。POSTPAID_BY_HOUR:按小時(shí)后付費(fèi)。 InstanceChargeType string `yaml:"InstanceChargeType"` } func InitConfigStruct(path string) *ConfigData { var ConfigData = &ConfigData{} vip := viper.New() vip.AddConfigPath(path) vip.SetConfigName("config") vip.SetConfigType("yaml") //嘗試進(jìn)行配置讀取 if err := vip.ReadInConfig(); err != nil { panic(err) } err := vip.Unmarshal(ConfigData) if err != nil { panic(err) } return ConfigData } func main(){ configData := InitConfigStruct("./data/") secretId := configData.Common.SecretId secretKey := configData.Common.SecretKey fmt.Printf("secretId:%s\n", secretId) fmt.Printf("secretKey:%s\n", secretKey) }
作者:周欽雄 出處:http://www.cnblogs.com/zhouqinxiong/ |
到此這篇關(guān)于Go讀取yaml文件到struct類的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Go讀取yaml文件 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
go單體日志采集zincsearch方案實(shí)現(xiàn)
這篇文章主要為大家介紹了go單體日志采集zincsearch方案實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07Go語言標(biāo)準(zhǔn)輸入輸出庫的基本使用教程
輸入輸出在任何一門語言中都必須提供的一個(gè)功能,下面這篇文章主要給大家介紹了關(guān)于Go語言標(biāo)準(zhǔn)輸入輸出庫的基本使用,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-02-02golang?gorm開發(fā)架構(gòu)及寫插件示例
這篇文章主要為大家介紹了golang?gorm開發(fā)架構(gòu)及寫插件的詳細(xì)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04Golang 中的可測(cè)試示例函數(shù)(Example Function)詳解
這篇文章詳細(xì)講解了 Golang 中的可測(cè)試示例函數(shù),示例函數(shù)類似于單元測(cè)試函數(shù),但沒有 *testing 類型的參數(shù),編寫示例函數(shù)也是很容易的,本文就通過代碼示例給大家介紹一下Golang的可測(cè)試示例函數(shù),需要的朋友可以參考下2023-07-07