Files
workspace/code/allapp/allapp-go/utils/responsex/index.go
T
2026-02-26 17:31:08 +08:00

73 lines
1.8 KiB
Go

package responsex
import "github.com/gofiber/fiber/v3"
// Result 响应结构
type Result struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
TrackId string `json:"trackId,omitempty"`
}
// 业务码
var BizCode = struct {
Success int // 成功
Unauthorized int // 未授权/Token失效
SpaceError int // 空间异常(已退出/被踢出等)
BusinessError int // 业务异常,例如参数错误、操作不允许
SystemError int // 系统异常,例如数据库崩溃、未知错误
}{
Success: 1000,
Unauthorized: 1001,
SpaceError: 1002,
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)
}
// Error 业务异常
func Error(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)
}
// SpaceError 空间异常
func SpaceError(c fiber.Ctx, msg string) error {
return Respond(c, BizCode.SpaceError, msg, nil)
}