electricity_bill_calc_service/router/router.go

84 lines
2.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package router
import (
"electricity_bill_calc/controller"
"electricity_bill_calc/logger"
"electricity_bill_calc/security"
"fmt"
"runtime"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/recover"
jsontime "github.com/liamylian/jsontime/v2/v2"
"go.uber.org/zap"
)
var json = jsontime.ConfigWithCustomTimeFormat
func init() {
timeZoneShanghai, _ := time.LoadLocation("Asia/Shanghai")
jsontime.AddTimeFormatAlias("simple_datetime", "2006-01-02 15:04:05")
jsontime.AddTimeFormatAlias("simple_date", "2006-01-02")
jsontime.AddLocaleAlias("shanghai", timeZoneShanghai)
}
func App() *fiber.App {
app := fiber.New(fiber.Config{ //创建fiber实例的时候选择配置选项
BodyLimit: 30 * 1024 * 1024, //设置请求正文允许的最大大小。
EnablePrintRoutes: true, //自定义方案,用于启动消息
EnableTrustedProxyCheck: false, //禁用受信代理
Prefork: false, //禁止预处理如果要启用预处理则需要通过shell脚本运行
ErrorHandler: errorHandler, //相应全局处理错误
JSONEncoder: json.Marshal, //json编码
JSONDecoder: json.Unmarshal, //json解码
})
app.Use(compress.New()) //压缩中间件
app.Use(recover.New(recover.Config{
EnableStackTrace: true,
StackTraceHandler: stackTraceHandler,
})) //恢复中间件
app.Use(logger.NewLogMiddleware(logger.LogMiddlewareConfig{
Logger: logger.Named("App"),
})) //日志中间件
app.Use(security.SessionRecovery) //会话恢复中间件
controller.InitializeUserHandlers(app)
controller.InitializeRegionHandlers(app)
controller.InitializeChargeHandlers(app)
controller.InitializeParkHandlers(app)
controller.InitializeTenementHandler(app)
controller.InitializeMeterHandlers(app)
controller.InitializeInvoiceHandler(app)
controller.InitializeTopUpHandlers(app)
controller.InitializeReportHandlers(app)
controller.InitializeWithdrawHandlers(app) // 公示撤回
controller.InitializeFoundationHandlers(app) // 基础数据
controller.InitializeStatisticsController(app) // 首页信息
controller.InitializeGmController(app) // 天神模式
return app
}
// 全局错误处理
func errorHandler(c *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
if e, ok := err.(*fiber.Error); ok {
code = e.Code
}
e := c.Status(code).SendString(err.Error())
if e != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
return nil
}
// 处理Recover中间件输出的栈追踪信息
func stackTraceHandler(c *fiber.Ctx, e interface{}) {
buf := make([]byte, 1024)
buf = buf[:runtime.Stack(buf, false)]
logger.Named("App", "StackTrace").Warn(fmt.Sprintf("panic: %+v", e), zap.ByteString("trace", buf), zap.Any("origin", e))
}