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{ BodyLimit: 10 * 1024 * 1024, EnablePrintRoutes: true, EnableTrustedProxyCheck: false, Prefork: false, ErrorHandler: errorHandler, JSONEncoder: json.Marshal, JSONDecoder: json.Unmarshal, }) 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.InitializeMeterHandlers(app) controller.InitializeInvoiceHandler(app) controller.InitializeTopUpHandlers(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)) }