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 //requestId
app.Use(requestid.New()) app.Use(requestid.New())
//recover //recover
app.Use(api.FibberRecover) app.Use(api.FibberRecoverHandler)
//requestId for gorm //requestId for gorm
app.Use(api.FibberUserCtxWithTrace) app.Use(api.FibberUserCtxWithTraceHandler)
} }
func routerInit() { func routerInit() {

View File

@ -3,7 +3,12 @@ package api
import ( import (
"context" "context"
"fmt"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
ctxLogger "github.com/luizsuper/ctxLoggers"
"go.uber.org/zap"
"runtime"
) )
// FiberErrHandler fiber 错误处理的中间件 // FiberErrHandler fiber 错误处理的中间件
@ -28,6 +33,11 @@ func FiberErrHandler(ctx *fiber.Ctx, err error) error {
// FibberRespHandler fiber resp的统一处理 // FibberRespHandler fiber resp的统一处理
func FibberRespHandler(c *fiber.Ctx) error { func FibberRespHandler(c *fiber.Ctx) error {
err := c.Next()
if err != nil {
return err
}
if respContentType := string(c.Response().Header.ContentType()); respContentType == fiber.MIMEApplicationJSON { if respContentType := string(c.Response().Header.ContentType()); respContentType == fiber.MIMEApplicationJSON {
resp := Response{ resp := Response{
Code: 0, Code: 0,
@ -40,22 +50,21 @@ func FibberRespHandler(c *fiber.Ctx) error {
return c.Next() return c.Next()
} }
// FibberRecover fiberPanicRecover // FibberRecoverHandler fiberPanicRecover
func FibberRecover(c *fiber.Ctx) error { func FibberRecoverHandler() fiber.Handler {
if respContentType := string(c.Response().Header.ContentType()); respContentType == fiber.MIMEApplicationJSON { return recover.New(recover.Config{
resp := Response{ EnableStackTrace: true,
Code: 0, StackTraceHandler: func(c *fiber.Ctx, e interface{}) {
Message: "", buf := make([]byte, 1024*1024)
Data: c.Response().Body(), buf = buf[:runtime.Stack(buf, false)]
} fmt.Printf("panic: %v\n%s\n", e, buf)
return c.JSON(resp) ctxLogger.FError(c, "panic", zap.String("", fmt.Sprintf("panic: %v\n%s\n", e, buf)))
},
})
} }
return c.Next() // FibberUserCtxWithTraceHandler 把fibberCtx的traceId 置入UserCtx中
} func FibberUserCtxWithTraceHandler(c *fiber.Ctx) error {
// FibberUserCtxWithTrace 把fibberCtx的traceId 置入UserCtx中
func FibberUserCtxWithTrace(c *fiber.Ctx) error {
c.SetUserContext(context.WithValue(context.Background(), fiber.HeaderXRequestID, c.Response().Header.Peek(fiber.HeaderXRequestID))) c.SetUserContext(context.WithValue(context.Background(), fiber.HeaderXRequestID, c.Response().Header.Peek(fiber.HeaderXRequestID)))
return c.Next() return c.Next()
} }