Go应用的灵活配置viper
Viper是一个完整的Go应用程序配置解决方案,它可以处理所有类型的配置需求和格式。
viper 的功能
viper 支持以下功能:
- 支持Yaml、Json、 TOML、HCL 等格式的配置
- 可以从文件、io、环境变量、command line中提取配置
- 支持自动转换的类型解析
- 可以远程从etcd中读取配置
安装
go get -u github.com/spf13/viper
示例
package main
import (
"github.com/spf13/viper"
"fmt"
)
var VP *viper.Viper
func AutoLoadConfig() error {
VP = viper.New()
//设置配置文件的名字
VP.SetConfigName("config")
//添加配置文件所在的路径
VP.AddConfigPath("./config/")
//设置配置文件类型
VP.SetConfigType("yaml")
if err := VP.ReadInConfig(); err != nil{
fmt.Printf("error: %s \n", err.Error());
return err
}
//获取系统环境变量
VP.BindEnv("GOPATH")
fmt.Printf("list: %+v, gopath: %s \n", VP.Get("information.list"), VP.Get("GOPATH"));
return nil;
}
config.yaml
TimeStamp: "2019-10-10 14:15:16"
Author: "Yisonli"
Information:
List:
- "One"
- "Two"
- "Three"
LuckyNumber: 7
运行结果
list: [One Two Three], gopath: /Users/yison/LocalProject/eclipse_work/go