u
This commit is contained in:
1 parent
f08db1959b
commit
c6671c8a8c
68 files changed
+13904
-1131
No files matched your search
@@ -0,0 +1,20 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
var validate = validator.New()
|
||||
|
||||
func BindAndValidate(c fiber.Ctx, v any) error {
|
||||
if err := c.Bind().Body(v); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validate.Struct(v); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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)
|
||||
}
|
||||
Reference in new issue
Block a user