栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Golang读取配置文件实现(yaml)

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Golang读取配置文件实现(yaml)

目录准备

在项目根目录新建config配置文件目录,同时创建一个yaml格式的配置文件config.yaml,写入一些测试数据

env:
  lang: golang
  system: win10

author: lauwen

apiTokenKey: Z2luLWNsaTIwMjEwNQ==
apiTokenExpireTime: 1440
apiTokenRebuildTime: 100

读取实现

安装

读取配置文件这里使用到spf13/viper这个库,先安装

go get -u github.com/spf13/viper

读取键值格式 

[配置文件名].[yaml文件具体配置],例如confing.yaml文件下env.lang配置,传递时写为config.env.lang

 

获取文件名filename和要获取的键名key

index := strings.Index(fileKey, ".")
fileName := fileKey[0:index]
key := fileKey[index+1:]

viper读取

// 初始化viper
viper := viper2.New()

// 设置配置文件名,即上一步提取的
viper.SetConfigName(fileName)

// 设置配置文件格式
viper.SetConfigType("yaml")

// 设置配置文件所在目录,这里固定为config,可以根据需要更改
viper.AddConfigPath("config")

具体实现代码

package config

import (
	viper2 "github.com/spf13/viper"
	"strings"
)

func Get(fileKey string) interface{}  {
	index := strings.Index(fileKey, ".")
	fileName := fileKey[0:index]
	key := fileKey[index+1:]

	viper := viper2.New()
	viper.SetConfigName(fileName)
	viper.SetConfigType("yaml")
	viper.AddConfigPath("config")

	if err := viper.ReadInConfig(); err != nil {
		panic(err.Error())
	}
	return viper.Get(key)
}

调用
config.Get("config.env.lang")

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903053.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号