1、yaml檔案準備
common:
secretid: AKIDxxxxx
secretKey: 3xgGxxxx
egion: ap-guangzhou
zone: ap-guangzhou-7
InstanceChargeType: POSTPAID_BY_HOUR
2、config配置類準備
可以通過在線配置工具轉換成struct
例如:https://www.printlove.cn/tools/yaml2go

代碼:
type ConfigData struct {
// 公共配置
Common Common `yaml:"common"`
}
type Common struct {
// 密鑰id,密鑰可前往官網控制臺 https://console.cloud.tencent.com/cam/capi 進行獲取
SecretId string `yaml:"secretid"`
// 密鑰key
SecretKey string `yaml:"secretKey"`
// 地域
Region string `yaml:"region"`
// 可用區
Zone string `yaml:"zone"`
//實體計費模式,取值范圍:PREPAID:預付費,即包年包月,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"`
// 可用區
Zone string `yaml:"zone"`
//實體計費模式,取值范圍:PREPAID:預付費,即包年包月,POSTPAID_BY_HOUR:按小時后付費,
InstanceChargeType string `yaml:"InstanceChargeType"`
}
func InitConfigStruct(path string) *ConfigData {
var ConfigData = https://www.cnblogs.com/zhouqinxiong/archive/2023/01/16/&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)
}
周欽雄技術分享
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542058.html
標籤:其他
下一篇:gRPC之初體驗
