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")

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值