🎨 逻辑修改,把依赖从写死改为配置

This commit is contained in:
李寻欢
2023-10-26 10:07:08 +08:00
parent 581faf974c
commit 8f15b58825
12 changed files with 179 additions and 19 deletions

View File

@@ -5,7 +5,9 @@ var Conf Config
// Config
// @description: 配置
type Config struct {
Task task `json:"task" yaml:"task"` // 定时任务配置
Task task `json:"task" yaml:"task"` // 定时任务配置
MySQL mysql `json:"mysql" yaml:"mysql"` // MySQL 配置
Wechat wechat `json:"wechat" yaml:"wechat"` // 微信助手
}
// task

View File

@@ -1,44 +0,0 @@
package config
import (
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"log"
)
// 配置管理工具
var vp *viper.Viper
// InitConfig
// @description: 初始化配置
func InitConfig() {
vp = viper.New()
vp.AddConfigPath(".") // 设置配置文件路径
vp.SetConfigName("config") // 设置配置文件名
vp.SetConfigType("yaml") // 设置配置文件类型
// 读取配置文件
if err := vp.ReadInConfig(); err != nil {
log.Panicf("读取配置文件失败: %v", err)
}
// 绑定配置文件
if err := vp.Unmarshal(&Conf); err != nil {
log.Panicf("配置文件解析失败: %v", err)
}
log.Printf("配置文件解析完成: %+v", Conf)
// 初始化数据库连接
//db.Init()
//redis.Init()
// 下面的代码是配置变动之后自动刷新的
vp.WatchConfig()
vp.OnConfigChange(func(e fsnotify.Event) {
// 绑定配置文件
if err := vp.Unmarshal(&Conf); err != nil {
log.Printf("配置文件更新失败: %v", err)
} else {
// 初始化数据库连接
//db.Init()
//redis.Init()
}
})
}

24
config/mysql.go Normal file
View File

@@ -0,0 +1,24 @@
package config
import (
"fmt"
)
// mysql
// @description: MySQL配置
type mysql struct {
Host string `mapstructure:"host" yaml:"host"` // 主机
Port int `mapstructure:"port" yaml:"port"` // 端口
User string `mapstructure:"user" yaml:"user"` // 用户名
Password string `mapstructure:"password" yaml:"password"` // 密码
Db string `mapstructure:"db" yaml:"db"` // 数据库名称
}
// GetDSN
// @description: 返回 MySQL 连接字符串
// @receiver c
// @return string
func (c mysql) GetDSN() string {
return fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8mb4&parseTime=True&loc=Local",
c.User, c.Password, c.Host, c.Port, c.Db)
}

33
config/wechat.go Normal file
View File

@@ -0,0 +1,33 @@
package config
import "strings"
// wxHelper
// @description: 微信助手
type wechat struct {
Host string `json:"host" yaml:"host"` // 接口地址
AutoSetCallback bool `json:"autoSetCallback" yaml:"autoSetCallback"` // 是否自动设置回调地址
Callback string `json:"callback" yaml:"callback"` // 回调地址
}
// Check
// @description: 检查配置是否可用
// @receiver w
// @return bool
func (w wechat) Check() bool {
if w.Host == "" {
return false
}
if w.AutoSetCallback && w.Callback == "" {
return false
}
return true
}
func (w wechat) GetURL(uri string) string {
host := w.Host
if !strings.HasPrefix(w.Host, "http://") {
host = "http://" + w.Host
}
return host + uri
}