backend/pkg/api/fiber.go

94 lines
2.2 KiB
Go

// Package api 关于所有第三方框架的二次封装
package api
import (
"context"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
ctxLogger "github.com/luizsuper/ctxLoggers"
"go.uber.org/zap"
"runtime"
)
// FiberMiddleWareErrHandler fiber 错误处理的中间件
func FiberMiddleWareErrHandler(ctx *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
msg := ""
if e, ok := err.(*fiber.Error); ok {
code = e.Code
msg = e.Message
}
if err != nil {
msg = err.Error()
}
return ctx.Status(code).JSON(Response{
Code: code,
Message: msg,
Data: nil,
})
}
// FibberMiddleWareRespHandler fiber resp的统一处理
func FibberMiddleWareRespHandler(c *fiber.Ctx) error {
err := c.Next()
if err != nil {
return err
}
if respContentType := string(c.Response().Header.ContentType()); respContentType == fiber.MIMEApplicationJSON {
resp := Response{
Code: 0,
Message: "",
Data: c.Response().Body(),
}
return c.JSON(resp)
}
return nil
}
// GetFibberRecoverConfig fiberPanicRecoverConfig
func GetFibberRecoverConfig() recover.Config {
return recover.Config{
EnableStackTrace: true,
StackTraceHandler: func(c *fiber.Ctx, e interface{}) {
buf := make([]byte, 1024*1024)
buf = buf[:runtime.Stack(buf, false)]
fmt.Printf("panic: %v\n%s\n", e, buf)
ctxLogger.FError(c, "panic", zap.String("", fmt.Sprintf("panic: %v\n%s\n", e, buf)))
},
}
}
// FibberUserCtxWithTraceHandler 把fibberCtx的traceId 置入UserCtx中
func FibberUserCtxWithTraceHandler(c *fiber.Ctx) error {
peek := c.Response().Header.Peek(fiber.HeaderXRequestID)
c.SetUserContext(context.WithValue(context.Background(), fiber.HeaderXRequestID, string(peek)))
return c.Next()
}
func NewFError(msg string) error {
return fiber.NewError(fiber.StatusInternalServerError, msg)
}
func NewFErrorWithCode(code int, msg string) error {
return fiber.NewError(code, msg)
}
func WarpFError(err error) error {
if err == nil {
return nil
}
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
func WarpFErrorWithCode(code int, err error) error {
if err == nil {
return nil
}
return fiber.NewError(code, err.Error())
}