generated from pkg/go-template
93 lines
2.1 KiB
Go
93 lines
2.1 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"
|
|
)
|
|
|
|
// FiberErrHandler fiber 错误处理的中间件
|
|
func FiberErrHandler(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,
|
|
})
|
|
}
|
|
|
|
// FibberRespHandler fiber resp的统一处理
|
|
func FibberRespHandler(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
|
|
}
|
|
|
|
// FibberRecoverHandler fiberPanicRecover
|
|
func FibberRecoverHandler() fiber.Handler {
|
|
return recover.New(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 {
|
|
c.SetUserContext(context.WithValue(context.Background(), fiber.HeaderXRequestID, c.Response().Header.Peek(fiber.HeaderXRequestID)))
|
|
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())
|
|
}
|