引言
Viper是Go应用程序的完整配置解决方案,包括
12-Factor
应用程序。它设计用于在应用程序中工作,可以处理所有类型的配置需求和格式。它支持:
- 设置默认值
- 读取JSON、TOML、YAML、HCL、envfile和Java properties属性配置文件
- 实时查看和重读配置文件(可选)
- 从环境变量中读取
- 从远程配置系统(etcd或Consor)读取数据,并观察变化
- 从命令行标志读取
- 从缓冲区读取
- 设置显式值
Github地址
:https://github.com/spf13/viper
基本用法
- 本文以读取toml格式的配置文件为例子
- 配置文件定义如下(config.toml)
[app]
port = 9000
init_models = false
loglevel = "debug"
logfile = "/tmp/app/log.log"
static_dir = "/tmp/app/static"
gateway = "localhost"
[secret]
jwt = "a-example-jwt-key"
package main
import (
"fmt"
"github.com/spf13/viper"
"io/ioutil"
"log"
"os"
"reflect"
"strings"
)
//配置文件结构体,配置文件上的内容需要一一对应,可多不可少
type Configure struct {
App struct {
InitModels bool `json:"init_models" remark:"是否初始化数据库模型" must:"false"`
Port int64 `json:"port" remark:"http端口"`
Loglevel string `json:"loglevel" remark:"日志级别"`
Logfile string `json:"logfile" remark:"日志文件"`
StaticDir string `json:"static_dir" remark:"静态文件目录"`
Gateway string `json:"gateway" remark:"网关服务器" must:"false"`
}
Secret struct {
JWT string `json:"jwt" remark:"jwt密钥"`
}
}
// 初始化viper
func initViper() {
viper.SetConfigName("config") //指定配置文件的文件名称(不需要指定配置文件的扩展名)
viper.AddConfigPath(".") // 设置配置文件和可执行二进制文件在用一个目录
viper.AutomaticEnv() //自动从环境变量读取匹配的参数
//读取-c输入的路径参数,初始化配置文件,如: ./main -c config.yaml
if len(os.Args) >= 3 {
if os.Args[1] == "-c" {