Go读取yaml文件到struct类
  bzPVctOlMIRE 2023年11月02日 88 0
Go

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 = &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)

}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  uGYzDadp0Cs7   2024年04月18日   78   0   0 Go
  hyrB1Ag4eVs8   2024年04月15日   69   0   0 Go
  dHUS172Lkv6A   2024年05月08日   174   0   0 Go
  YFCZjJLTjJgW   2024年05月04日   51   0   0 Go
  YFCZjJLTjJgW   2024年05月17日   59   0   0 Go
  uGYzDadp0Cs7   2024年04月16日   118   0   0 Go
  YFCZjJLTjJgW   2024年05月17日   59   0   0 Go
bzPVctOlMIRE
作者其他文章 更多