generated from pkg/go-template
84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
|
// Package api 关于所有第三方框架的二次封装
|
||
|
package api
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"github.com/gofiber/fiber/v2"
|
||
|
)
|
||
|
|
||
|
// 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 {
|
||
|
if respContentType := string(c.Response().Header.ContentType()); respContentType == fiber.MIMEApplicationJSON {
|
||
|
resp := Response{
|
||
|
Code: 0,
|
||
|
Message: "",
|
||
|
Data: c.Response().Body(),
|
||
|
}
|
||
|
return c.JSON(resp)
|
||
|
}
|
||
|
|
||
|
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)
|
||
|
}
|
||
|
|
||
|
return c.Next()
|
||
|
}
|
||
|
|
||
|
// FibberUserCtxWithTrace 把fibberCtx的traceId 置入UserCtx中
|
||
|
func FibberUserCtxWithTrace(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())
|
||
|
}
|