101 lines
2.4 KiB
Go
101 lines
2.4 KiB
Go
package initialize
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/redis/go-redis/v9"
|
|
"golang.zx2c4.com/wireguard/wgctrl"
|
|
"gopkg.in/yaml.v3"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
"wireguard-dashboard/client"
|
|
"wireguard-dashboard/config"
|
|
)
|
|
|
|
// Init
|
|
// @description: 初始化
|
|
func Init() {
|
|
initConfig() // 读取配置文件
|
|
initWireguard() // 初始化wireguard客户端
|
|
initDatabase() // 初始化数据库
|
|
initRedis() // 初始化redis
|
|
}
|
|
|
|
// initConfig
|
|
// @description: 初始化配置
|
|
func initConfig() {
|
|
configBytes, err := os.ReadFile("app.yaml")
|
|
if err != nil {
|
|
log.Panicf("读取配置文件失败: %v", err.Error())
|
|
}
|
|
|
|
err = yaml.Unmarshal(configBytes, &config.Config)
|
|
if err != nil {
|
|
log.Panicf("解析配置文件失败: %v", err.Error())
|
|
}
|
|
}
|
|
|
|
// InitWireguard
|
|
// @description: 初始化wireguard客户端
|
|
func initWireguard() {
|
|
c, err := wgctrl.New()
|
|
if err != nil {
|
|
log.Panicf("初始化wireguard客户端失败: %v", err.Error())
|
|
}
|
|
|
|
client.WireguardClient = c
|
|
}
|
|
|
|
// initDatabase
|
|
// @description: 初始化数据库
|
|
func initDatabase() {
|
|
gormLogger := logger.New(
|
|
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
|
|
logger.Config{
|
|
SlowThreshold: time.Second, // Slow SQL threshold
|
|
LogLevel: logger.Silent, // Log level
|
|
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
|
|
ParameterizedQueries: true, // Don't include params in the SQL log
|
|
Colorful: true, // Disable color
|
|
},
|
|
)
|
|
|
|
// 不同驱动提供
|
|
var dbDialector gorm.Dialector
|
|
switch config.Config.Database.Driver {
|
|
case "mysql":
|
|
dbDialector = mysql.Open(config.Config.Database.GetDSN())
|
|
case "pgsql":
|
|
dbDialector = postgres.Open(config.Config.Database.GetDSN())
|
|
case "sqlite":
|
|
dbDialector = sqlite.Open(config.Config.Database.GetDSN())
|
|
}
|
|
|
|
db, err := gorm.Open(dbDialector, &gorm.Config{
|
|
Logger: gormLogger,
|
|
})
|
|
|
|
if err != nil {
|
|
log.Panicf("链接数据库[%s]失败:%v", config.Config.Database.Driver, err.Error())
|
|
}
|
|
|
|
client.DB = db
|
|
}
|
|
|
|
// initRedis
|
|
// @description: 初始化redis
|
|
func initRedis() {
|
|
c := redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%d", config.Config.Redis.Host, config.Config.Redis.Port),
|
|
Password: config.Config.Redis.Password,
|
|
DB: config.Config.Redis.Db,
|
|
})
|
|
|
|
client.Redis = c
|
|
}
|