Go读取yaml文件到struct类
Go读取yaml文件到struct类
1、yaml文件准备
common:secretid: AKIDxxxxxsecretKey: 3xgGxxxxregion: ap-guangzhouzone: ap-guangzhou-7InstanceChargeType: 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"`// 密钥keySecretKey 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 mainimport ("bufio""github.com/spf13/viper""io""os""strings")type ConfigData struct {// 公共配置Common Common `yaml:"common"`}type Common struct {// 密钥id。SecretId string `yaml:"secretid"`// 密钥keySecretKey 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 = &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.SecretIdsecretKey := configData.Common.SecretKeyfmt.Printf("secretId:%s\n", secretId)fmt.Printf("secretKey:%s\n", secretKey)}
或者
package initialize
import (
"fmt"
"os"
"gitlab.itvgame.org/storage-worker/global"
"gitlab.itvgame.org/storage-worker/utils"
"gopkg.in/yaml.v2"
)
// Config .
func Config() {
// 1. read yaml, instance config.Zap
yfile, err := os.Open(utils.ConfigFile)
if err != nil {
global.Zap.Error(fmt.Sprintf("%v", err))
os.Exit(1)
}
defer yfile.Close()
ydecode := yaml.NewDecoder(yfile)
ydecode.Decode(&global.Config)
}

浙公网安备 33010602011771号