64 lines
1.5 KiB
Go
64 lines
1.5 KiB
Go
package httpx
|
|
|
|
import "github.com/gofiber/fiber/v3"
|
|
|
|
type Result struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data"`
|
|
TrackId string `json:"track_id,omitempty"`
|
|
}
|
|
|
|
var BizCode = struct {
|
|
Success int // 成功
|
|
Unauthorized int // 未授权/Token失效
|
|
BusinessError int // 业务异常,例如参数错误、操作不允许
|
|
SystemError int // 系统异常,例如数据库崩溃、未知错误
|
|
}{
|
|
Success: 1000,
|
|
Unauthorized: 1001,
|
|
BusinessError: 2000,
|
|
SystemError: 3000,
|
|
}
|
|
|
|
// ------------------- 统一响应方法 -------------------
|
|
|
|
// Respond 返回通用响应,code和msg必填,data可选
|
|
func Respond(c fiber.Ctx, code int, msg string, data interface{}) error {
|
|
trackId := ""
|
|
if v := c.Context().Value("request_id"); v != nil {
|
|
if s, ok := v.(string); ok {
|
|
trackId = s
|
|
}
|
|
}
|
|
|
|
return c.JSON(Result{
|
|
Code: code,
|
|
Message: msg,
|
|
Data: data,
|
|
TrackId: trackId,
|
|
})
|
|
}
|
|
|
|
// ------------------- 便捷封装 -------------------
|
|
|
|
// OK 成功响应
|
|
func OK(c fiber.Ctx, data interface{}) error {
|
|
return Respond(c, BizCode.Success, "success", data)
|
|
}
|
|
|
|
// Fail 业务异常
|
|
func Fail(c fiber.Ctx, msg string) error {
|
|
return Respond(c, BizCode.BusinessError, msg, nil)
|
|
}
|
|
|
|
// SystemError 系统异常
|
|
func SystemError(c fiber.Ctx, msg string) error {
|
|
return Respond(c, BizCode.SystemError, msg, nil)
|
|
}
|
|
|
|
// Unauthorized 授权失败
|
|
func Unauthorized(c fiber.Ctx, msg string) error {
|
|
return Respond(c, BizCode.Unauthorized, msg, nil)
|
|
}
|