Go实战(一)--读取Yaml格式的配置文件

mb5fcdf38f75bdc · · 4506 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Go实战(一)--读取Yaml格式的配置文件

前言

在项目中,往往有些属性是不能硬编码到代码中的,例如数据库链接、账号信息等。因此需要我们能在将这些数据写到配置文件中,在项目中读取。

本文仅用于记录如何使用yaml.v2Viper读取配置文件。

代码实战

创建结构体

编写config.yml,以及对应的结构体config.go,代码如下。

app:
  host: 127.0.0.1
  port: 3306
  username: admin
  password: admin
log:
  suffix: log
  maxSize: 5

package config


package configtype Config struct {
	App *App `yaml:"app"`
	Log *Log `yaml:"log"`}type App struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`}type Log struct {
	Suffix  string `yaml:"suffix"`
	MaxSize int    `yaml:"maxSize"`}


使用yaml.v2读取配置文件

1、运行以下命令,导入yaml.v2。

go get gopkg.in/yaml.v2

2、使用ioutil导入配置文件,使用yaml.Unmarshal将配置文件读取到结构体中,示例代码如下。

package mainimport (
	"GoReadConfig/config"
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil")func InitConfig() {
	yamlFile, err := ioutil.ReadFile("./config/config.yml")
	if err != nil {
		fmt.Println(err.Error())
	}
	var _config *config.Config
	err = yaml.Unmarshal(yamlFile, &_config)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Printf("config.app: %#v\n", _config.App)
	fmt.Printf("config.log: %#v\n", _config.Log)}func main() {
	InitConfig()}

使用Viper读取配置文件

yaml.v2只能读取yaml格式的文件,而Viper可以处理多种格式的配置,目前已支持从JSON、TOML、YAML、HCL、INI和Java properties文件中读取配置数据。

Viper还能监视配置文件的变动、重新读取配置文件。在项目中可以用作热加载。

其他的特性,可以参考github上Viper的官方说明,此处不再赘述。

1、运行以下命令,导入Viper

go get github.com/spf13/viper

2、使用Viper导入配置文件,并将配置文件读取到结构体中,示例代码如下。

package mainimport (
	"GoReadConfig/config"
	"fmt"
	"github.com/spf13/viper")func InitConfigByViper() {

	viper.SetConfigType("yaml")
	viper.SetConfigFile("./config/config.yml")

	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err.Error())
	}
	var _config *config.Config
	err = viper.Unmarshal(&_config)
	if err != nil {
		fmt.Println(err.Error())
	}

	fmt.Printf("config.app: %#v\n", _config.App)
	fmt.Printf("config.log: %#v\n", _config.Log)}func main() {
	InitConfigByViper()}



有疑问加站长微信联系(非本文作者)

本文来自:51CTO博客

感谢作者:mb5fcdf38f75bdc

查看原文:Go实战(一)--读取Yaml格式的配置文件

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

4506 次点击  ∙  1 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传