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