Golang 如何使用 viper 读取配置文件

428 阅读1分钟

Viper GItHub地址

下载依赖:

    go get github.com/spf13/viper // 下载依赖

yml 文件放在项目根路径下 (config.yml)

service:
  # 端口
  port: ":8080"

mysql:
  # 用户名
  username: root
  # 密码
  password: 111111
  # 数据库名
  database: go-go
  # 主机地址
  host: localhost
  # 端口
  port: 3306
  # 连接字符串参数
  query: parseTime=True&loc=Local&timeout=10000ms
  # 是否打印日志
  log-mode: true
  # 数据库表前缀
  table-prefix: ad
  # 编码方式
  charset: utf8mb4
  # 字符集
  collation: utf8mb4_general_ci

logs:
  # 路径
  path: logs
  # 文件大小(Mb)
  max-size: 60
  # 备份数量
  max-backups: 60
  # 保存时间
  max-age: 7
  # 是否压缩
  gzip: false


完整代码示例:

package config

import (
	"fmt"
	"os"

	"github.com/spf13/viper"
        "github.com/fsnotify/fsnotify"
)

var Conf = new(config)

type config struct {
	Logs *LogsConfig `mapstructure:"logs" json:"logs"`
}
// 以zap logger为例
// viper集成了mapstructure 直接使用就好。
type LogsConfig struct {
	Path       string        `mapstructure:"path" json:"path"`
	MaxSize    int           `mapstructure:"max-size" json:"maxSize"`
	MaxBackups int           `mapstructure:"max-backups" json:"maxBackups"`
	MaxAge     int           `mapstructure:"max-age" json:"maxAge"`
	Gzip       bool          `mapstructure:"gzip" json:"gzip"`
}
// 代码可以抽到config文件中(config/config.go) 然后在main 中Init下就好
func main() {
	// 拿到当前工作目录
	workDir, err := os.Getwd()
	if err != nil {
		panic(fmt.Errorf("fatal error read app directory: %s", err))
	}
	// 配置文件名称
	viper.SetConfigFile("config.yml")
	// 添加搜素路径
	viper.AddConfigPath(workDir)
	// 读取配置信息
	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("fatal error read config: %s", err))
	}

	// 热更新配置
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		if err := viper.Unmarshal(Conf); err != nil {
			panic(fmt.Errorf("fatal error hot update config: %s", err))
		}
	})

	// 读取的配置信息保存至全局Conf中就可以在全局使用
        // 就不用使用viper.GetString() 不然还得区分类型读取麻烦
	if err := viper.Unmarshal(Conf); err != nil {
		panic(fmt.Errorf("fatal error init config: %s", err))
	}
        
        fmt.Println(Conf.Logs.Path)
}

这里贴一下源代码仓库,欢迎自取 Let·s goLang