2023-02-26 02:50:56 +08:00
|
|
|
package app
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
"matrix-middle-service/internel/route"
|
|
|
|
"matrix-middle-service/pkg/config"
|
2023-02-26 21:10:43 +08:00
|
|
|
"matrix-middle-service/pkg/database"
|
2023-02-26 02:50:56 +08:00
|
|
|
"matrix-middle-service/pkg/logger"
|
2023-02-26 21:10:43 +08:00
|
|
|
fib "matrix-middle-service/pkg/utils/fiber"
|
2023-02-26 23:48:03 +08:00
|
|
|
"matrix-middle-service/pkg/utils/nanoid"
|
2023-02-26 23:25:20 +08:00
|
|
|
"matrix-middle-service/pkg/utils/sonyflake"
|
2023-02-26 02:50:56 +08:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var app *fiber.App
|
|
|
|
var conf = new(config.Conf)
|
|
|
|
|
|
|
|
func CreateApp(c *config.Conf) *fiber.App {
|
|
|
|
return fiber.New(fiber.Config{
|
|
|
|
JSONEncoder: json.Marshal,
|
|
|
|
JSONDecoder: json.Unmarshal,
|
|
|
|
Prefork: c.Server.PreFork,
|
|
|
|
CaseSensitive: c.Server.CaseSensitive,
|
|
|
|
StrictRouting: c.Server.StrictRouting,
|
|
|
|
ServerHeader: c.Server.ServerHeader,
|
2023-02-27 16:10:20 +08:00
|
|
|
ErrorHandler: route.GlobalErrorHandler(),
|
2023-02-26 02:50:56 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func Run() {
|
|
|
|
err := viper.Unmarshal(conf)
|
|
|
|
if err != nil {
|
|
|
|
logger.Log().Fatalf("配置文件解析失败: %s, 请检查配置是否有误", err)
|
|
|
|
}
|
|
|
|
Shutdown()
|
|
|
|
|
2023-02-26 21:10:43 +08:00
|
|
|
// 初始化数据源
|
|
|
|
fib.Exec(func() {
|
2023-02-26 23:25:20 +08:00
|
|
|
InitApp(conf)
|
2023-02-26 21:10:43 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
// 创建 fiber 服务器
|
|
|
|
app = CreateApp(conf)
|
|
|
|
// 设置路由
|
|
|
|
route.SetupRoute(app, conf)
|
2023-02-26 02:50:56 +08:00
|
|
|
|
2023-02-26 21:10:43 +08:00
|
|
|
// 启动完成
|
2023-02-26 02:50:56 +08:00
|
|
|
app.Hooks().OnListen(func() error {
|
2023-02-26 21:10:43 +08:00
|
|
|
fib.Exec(func() {
|
|
|
|
logger.Log().Info("[√] [服务启动完成]")
|
|
|
|
})
|
2023-02-26 02:50:56 +08:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err := app.Listen(conf.Server.Addr); err != nil {
|
|
|
|
logger.Log().Fatalf("[x] [Fiber] 致命错误: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-26 23:25:20 +08:00
|
|
|
func InitApp(conf *config.Conf) {
|
|
|
|
database.Init(conf.DataSources)
|
|
|
|
if err := database.Open(); err != nil {
|
|
|
|
logger.Log().Fatal(err)
|
|
|
|
}
|
|
|
|
|
2023-02-26 23:48:03 +08:00
|
|
|
sonyflake.Init(conf.SonyFlake)
|
|
|
|
nanoid.Init(conf.NanoIdConfig)
|
2023-02-26 23:25:20 +08:00
|
|
|
}
|
|
|
|
|
2023-02-26 02:50:56 +08:00
|
|
|
func Shutdown() {
|
|
|
|
if app == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-02-26 21:34:53 +08:00
|
|
|
fib.Exec(func() {
|
|
|
|
database.Close()
|
|
|
|
})
|
|
|
|
|
|
|
|
logger.Log().Info("关闭服务")
|
2023-02-26 02:50:56 +08:00
|
|
|
timeout := 5 * time.Second
|
|
|
|
err := app.ShutdownWithTimeout(timeout)
|
|
|
|
if err != nil {
|
|
|
|
logger.Log().Fatal(err)
|
|
|
|
}
|
|
|
|
}
|