fix: 整理pkg
continuous-integration/drone/push Build is passing Details

master
liuhaotian 2022-01-13 14:48:28 +08:00
parent bb60689055
commit 3f060be9b9
2 changed files with 25 additions and 16 deletions

View File

@ -52,9 +52,9 @@ func appInit() {
//requestId
app.Use(requestid.New())
//recover
app.Use(api.FibberRecover)
app.Use(api.FibberRecoverHandler)
//requestId for gorm
app.Use(api.FibberUserCtxWithTrace)
app.Use(api.FibberUserCtxWithTraceHandler)
}
func routerInit() {

View File

@ -3,7 +3,12 @@ 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 错误处理的中间件
@ -28,6 +33,11 @@ func FiberErrHandler(ctx *fiber.Ctx, err error) error {
// 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,
@ -40,22 +50,21 @@ func FibberRespHandler(c *fiber.Ctx) error {
return c.Next()
}
// FibberRecover fiberPanicRecover
func FibberRecover(c *fiber.Ctx) error {
if respContentType := string(c.Response().Header.ContentType()); respContentType == fiber.MIMEApplicationJSON {
resp := Response{
Code: 0,
Message: "",
Data: c.Response().Body(),
}
return c.JSON(resp)
// 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)))
},
})
}
return c.Next()
}
// FibberUserCtxWithTrace 把fibberCtx的traceId 置入UserCtx中
func FibberUserCtxWithTrace(c *fiber.Ctx) error {
// 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()
}