30

Golang项目中引入yaml.v2配置文件

 3 years ago
source link: https://studygolang.com/articles/30999
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在Go语言项目中,常用的配置文件yaml、toml、json、xml、ini几种,因为本章主要讲解yaml配置文件的使用方法,其他几种配置文件在这里就不展开了介绍了,大家有兴趣可以自行百度。

yaml文件的语法网上有很多的教程,大家自行百度,这里也推荐两个链接:

yaml文件解析使用的是github上第三方开源框架 gopkg.in/yaml.v2 ,下面详细介绍安装和使用的方法:

1. 在项目的根目录执行如下命令:

go get gopkg.in/yaml.v2

2. 在项目的根目录创建conf.yaml文件,并添加以下内容:

service:
  url: https://127.0.0.1:8080
  host: 127.0.0.1
  subscriptions: [{
    topic: "orders_create",
    address: "https://127.0.0.1:8080/orders/creat"
  },{
    topic: "orders_submit",
    address: "https://127.0.0.1:8080/orders/submit"
  }
  ]

3. 在项目的main.go文件中导入头文件:

import (
  ...
   "gopkg.in/yaml.v2"
  ...
)

4. 创建struct数据结构:

//定义conf类型
//类型里的属性,全是配置文件里的属性
type Conf struct {
   Service   Serivce `yaml:"service"`
}

type Serivce struct {
   Url       string `yaml:"url"`
   Host     string `yaml:"host"`
   Topics []Topic `yaml:"subscriptions"`
}

type Topic struct {
   Topic  string `yaml:"topic"`
   Address string `yaml:"address"`
}

5. 添加读取配置文件以及解析数据结构的代码:

//读取Yaml配置文件,
//并转换成conf对象
func (conf *Conf) getConf() *Conf {
   //应该是 绝对地址
   yamlFile, err := ioutil.ReadFile("conf.yaml")
   if err != nil {
      fmt.Println(err.Error())
   }
   err = yaml.Unmarshal(yamlFile, conf)
   if err != nil {
      fmt.Println(err.Error())
   }
   return conf
}

6. 在程序中调用配置读取的接口并打印输出:

func main() {
   var conf Conf
   conf.getConf()
   var service = conf.Serivce
   fmt.Println("Shopify Url=" + service.Url)
   fmt.Println("Shopify Version=" + service.Host)
}

参考链接: https://blog.csdn.net/wade3015/article/details/83351776

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK