Go讀取yaml文件到struct類的實現(xiàn)方法
更新時間:2023年01月17日 08:26:37 作者:周欽雄
本文主要介紹了Go讀取yaml文件到struct類,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
1、yaml文件準備
common: secretid: AKIDxxxxx secretKey: 3xgGxxxx egion: ap-guangzhou zone: ap-guangzhou-7 InstanceChargeType: POSTPAID_BY_HOUR
2、config配置類準備
可以通過在線配置工具轉(zhuǎn)換成struct
例如:https://www.printlove.cn/tools/yaml2go

代碼:
type ConfigData struct {
// 公共配置
Common Common `yaml:"common"`
}
type Common struct {
// 密鑰id。密鑰可前往官網(wǎng)控制臺 https://console.cloud.tencent.com/cam/capi 進行獲取
SecretId string `yaml:"secretid"`
// 密鑰key
SecretKey string `yaml:"secretKey"`
// 地域
Region string `yaml:"region"`
// 可用區(qū)
Zone string `yaml:"zone"`
//實例計費模式。取值范圍:PREPAID:預(yù)付費,即包年包月。POSTPAID_BY_HOUR:按小時后付費。
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"`
//實例計費模式。取值范圍:PREPAID:預(yù)付費,即包年包月。POSTPAID_BY_HOUR:按小時后付費。
InstanceChargeType string `yaml:"InstanceChargeType"`
}
func InitConfigStruct(path string) *ConfigData {
var ConfigData = &ConfigData{}
vip := viper.New()
vip.AddConfigPath(path)
vip.SetConfigName("config")
vip.SetConfigType("yaml")
//嘗試進行配置讀取
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類的實現(xiàn)方法的文章就介紹到這了,更多相關(guān)Go讀取yaml文件 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang?gorm開發(fā)架構(gòu)及寫插件示例
這篇文章主要為大家介紹了golang?gorm開發(fā)架構(gòu)及寫插件的詳細示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04
Golang 中的可測試示例函數(shù)(Example Function)詳解
這篇文章詳細講解了 Golang 中的可測試示例函數(shù),示例函數(shù)類似于單元測試函數(shù),但沒有 *testing 類型的參數(shù),編寫示例函數(shù)也是很容易的,本文就通過代碼示例給大家介紹一下Golang的可測試示例函數(shù),需要的朋友可以參考下2023-07-07

