4-测试viper读取配置文件数据 --开源项目obtain_data测试
1.修改main.go文件的init函数
/main.go
// 这里就讲讲mysql的配置
func init() {
err := global.SetupSetting()
if err != nil {
log.Fatalf("init.setupSetting err: %v", err)
}
//logger
err = global.SetupLogger()
if err != nil {
log.Fatalf("init.SetupLogger err: %v", err)
}
err = global.SetupDBLink()
if err != nil {
log.Fatalf("init.setupDBEngine err: %v", err)
}
err = global.SetupRedisDb()
if err != nil {
log.Fatalf("init.SetupRedisDb err: %v", err)
}
err = global.SetupGlobalCache()
if err != nil {
log.Fatalf("init.SetupGlobalCache err: %v", err)
}
global.Logger.Infof("------应用init结束")
}
2.修改db.go文件
/global/db.go
// 连接到数据库
func SetupDBLink() error {
var err error
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local",
DatabaseSetting.UserName,
DatabaseSetting.Password,
DatabaseSetting.Host,
DatabaseSetting.DBName,
DatabaseSetting.Charset,
DatabaseSetting.ParseTime,
)
DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
DryRun: false, //生成 SQL 但不执行
NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 单数表名
},
})
if err != nil {
return err
} else {
return nil
}
}
3.增加pkg设置文件
/pkg/setting/setting.go
package setting
import (
"github.com/spf13/viper"
)
type Setting struct {
vp *viper.Viper
}
var sections = make(map[string]interface{})
//读取配置
func NewSetting() (*Setting, error) {
vp := viper.New()
vp.SetConfigName("config")
vp.AddConfigPath("config")
vp.SetConfigType("yaml")
err := vp.ReadInConfig()
if err != nil {
return nil, err
}
s := &Setting{vp}
return s, nil
}
//读取指定的一段
func (s *Setting) ReadSection(k string, v interface{}) error {
err := s.vp.UnmarshalKey(k, v)
if err != nil {
return err
}
if _, ok := sections[k]; !ok {
sections[k] = v
}
return nil
}
func (s *Setting) ReloadAllSection() error {
for k, v := range sections {
err := s.ReadSection(k, v)
if err != nil {
return err
}
}
return nil
}
4.增加全局设置文件
/global/setting.go
package global
import (
"time"
"gitee.com/wao520/obtain_data/pkg/setting"
)
// 服务器配置
type ServerSettingS struct {
RunMode string
HttpPort string
ReadTimeout time.Duration
WriteTimeout time.Duration
}
// 数据库配置
type DatabaseSettingS struct {
DBType string
UserName string
Password string
Host string
DBName string
Charset string
ParseTime bool
MaxIdleConns int
MaxOpenConns int
}
type RedisSettingS struct {
Addr string
Password string
}
// 日志配置
type LogSettingS struct {
LogFilePath string //保存到的目录
LogInfoFileName string //info级日志文件的名字
LogWarnFileName string //warn级日志文件的名字
LogFileExt string //文件的扩展名
}
// 定义全局变量
var (
ServerSetting *ServerSettingS
DatabaseSetting *DatabaseSettingS
RedisSetting *RedisSettingS
LogSetting *LogSettingS
)
// 读取配置到全局变量
func SetupSetting() error {
s, err := setting.NewSetting()
if err != nil {
return err
}
err = s.ReadSection("Database", &DatabaseSetting)
if err != nil {
return err
}
err = s.ReadSection("Server", &ServerSetting)
if err != nil {
return err
}
err = s.ReadSection("Redis", &RedisSetting)
if err != nil {
return err
}
err = s.ReadSection("Log", &LogSetting)
if err != nil {
return err
}
//fmt.Println("setting:")
//fmt.Println(ServerSetting)
//fmt.Println(DatabaseSetting)
return nil
}
5.增加配置文件
/config/config.yaml
Database:
DBType: mysql
UserName: root
Password: 123456
Host: 127.0.0.1:3306
DBName: obtain_data
Charset: utf8mb4
ParseTime: True
MaxIdleConns: 10
MaxOpenConns: 30
Server:
RunMode: debug
HttpPort: 8000
ReadTimeout: 60
WriteTimeout: 60
Redis:
Addr: 127.0.0.1:6379
Password:
Log:
LogFilePath: ./logs
LogInfoFileName: info
LogWarnFileName: warn
LogFileExt: log
3.获取开源项目
a.gin框架用viper读取配置文件数据
b.本测试代码下载