添加文件: server_tb_LinkedMall/internal/middleware/middleware.go
This commit is contained in:
parent
21250b4b28
commit
dd117b3da5
|
|
@ -0,0 +1,49 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// RequestID 为每个请求注入RequestID
|
||||
func RequestID() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
rid := c.Get("X-Request-Id")
|
||||
if rid == "" {
|
||||
rid = uuid.New().String()
|
||||
}
|
||||
c.Set("X-Request-Id", rid)
|
||||
c.Locals("requestId", rid)
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// StandardResponse 统一响应格式中间件
|
||||
func StandardResponse() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
// 先执行handler
|
||||
err := c.Next()
|
||||
if err != nil {
|
||||
// 处理handler返回的错误
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"Success": false,
|
||||
"Code": "INTERNAL_ERROR",
|
||||
"Message": err.Error(),
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// CORS 跨域中间件
|
||||
func CORS() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Request-Id")
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue