配置文件config.yml

mysql:
type: mysql
dsn: "user:pass@tcp(localhost:30306)/db_name?charset=utf8&parseTime=True&loc=Local"
maxopen: 100
maxidle: 10
maxlifetime: 300
redis:
host: 127.0.0.1
port: 3306

读取配置文件

package config

import (
"github.com/spf13/viper"
"path"
"runtime"
"time"
) type mysqlConfig struct { // 配置属性跟类型字段不同名是要加下面这个tag
Type string `mapstructure:"type"`
DSN string `mapstructure:"dsn"`
MaxOpenConn int `mapstructure:"maxopen"`
MaxIdleConn int `mapstructure:"maxidle"`
MaxLifeTime time.Duration `mapstructure:"maxlifetime"`
}
type redisConfig struct { // 配置属性跟类型字段不同名是要加下面这个tag
Host string `mapstructure:"host"`
Port string `mapstructure:"port"`
} var Mysql *mysqlConfig
var Redis *redisConfig func init() {
// 获取当前文件的路径
_, filename, _, _ := runtime.Caller(0)
// 配置文件目录的路径
configBaseDir := path.Dir(filename)
vp := viper.New()
vp.AddConfigPath(configBaseDir)
vp.SetConfigType("yaml")
err := vp.ReadInConfig()
if err != nil {
panic(err)
}
vp.UnmarshalKey("mysql", &Mysql)
vp.UnmarshalKey("redis", &Redis)
Mysql.MaxLifeTime *= time.Second
}

调用配置内容

import (
"fmt"
"lianxi/config"
) func main() {
fmt.Println(config.Redis.Port)
fmt.Println(config.Mysql.Type)
}

参考文档 https://zhuanlan.zhihu.com/p/485608958 https://www.cnblogs.com/randysun/p/15889494.html

最新文章

  1. Hibernate操作指南-搭建一个简单的示例(基于原生API和注解)
  2. 关于python中文件导入的若干问题
  3. SQLMAP使用笔记
  4. sql server2008企业版和标准版
  5. 自定义FragmentTabHost--实现View重复加载问题
  6. linux设备驱动归纳总结(四):5.多处理器下的竞态和并发【转】
  7. UVa 489,紫书P79,刽子手游戏
  8. 轻松学习Linux之VI编辑器的使用
  9. 【个人笔记】003-PHP基础-01-PHP快速入门-03-PHP环境搭建
  10. [转] Android进阶——安卓接入微信,获取OpenID
  11. Shell基本的命令
  12. KVO详解
  13. sort详解
  14. codeforces 339C Xenia and Bit Operations(线段树水题)
  15. HTML 5 JavaScript初步 编译运行.doc
  16. TabHost 简单用法
  17. IOS中Key-Value Coding (KVC)的使用具体解释
  18. grid实例(Asp.net)
  19. POJ 3683 Priest John's Busiest Day / OpenJ_Bailian 3788 Priest John's Busiest Day(2-sat问题)
  20. 史上最全PMP备考考点全攻略(上篇-五大过程组,附赠资料)

热门文章

  1. Spring(Ioc DI、Spring的继承-依赖)
  2. kali linux 使用教程
  3. vue2安装sass 预编译
  4. js的map、filter的用法
  5. 通过 Blob 创建下载文件
  6. mysql-8版本优化建议
  7. 关于Intent Uri页面跳转
  8. 图 -拓扑 topo
  9. Codeforces 1492D、Genius's Gambit
  10. SQL group by date (hour),数据库按小时分组统计数据量