wireguard-dashboard/initialize/init.go
coward 8fb39958d2
All checks were successful
continuous-integration/drone/tag Build is passing
🎨
2024-05-09 09:39:52 +08:00

127 lines
2.9 KiB
Go

package initialize
import (
"fmt"
"gitee.ltd/lxh/logger"
"github.com/cowardmrx/go_aliyun_oss"
"github.com/glebarez/sqlite"
"github.com/go-resty/resty/v2"
"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/gorm"
"log"
"os"
"wireguard-dashboard/client"
"wireguard-dashboard/config"
)
// Init
// @description: 初始化
func Init() {
initLogger() // 初始化日志
initConfig() // 读取配置文件
initWireguard() // 初始化wireguard客户端
initDatabase() // 初始化数据库
initRedis() // 初始化redis
initHttpClient() // 初始化http客户端
initOSS() // 初始化oss客户端链接
}
// 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() {
// 不同驱动提供
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: logger.DefaultGormLogger(),
})
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
}
// initHttpClient
// @description: 初始化http客户端
func initHttpClient() {
client.HttpClient = resty.New()
}
// initOSS
// @description: 初始化oss客户端
func initOSS() {
if config.Config.File.Type != "oss" {
return
}
ossConfig := &go_aliyun_oss.AliOssConfig{
EndPoint: config.Config.File.Endpoint,
AccessKeyId: config.Config.File.AccessId,
AccessKeySecret: config.Config.File.AccessSecret,
BucketName: config.Config.File.BucketName,
OriginalFileName: false,
}
ossClient := ossConfig.CreateOssConnect()
client.OSS = ossClient
}
// initLogger
// @description: 初始化日志
func initLogger() {
logger.InitLogger(logger.LogConfig{
Mode: logger.Dev,
FileEnable: true,
})
}