feat: add module resp

This commit is contained in:
zhaoyupeng
2025-07-02 14:28:35 +08:00
parent b6ee2966cf
commit c1edd8f34d
3 changed files with 190 additions and 0 deletions

56
resp/error.go Normal file
View File

@ -0,0 +1,56 @@
package resp
import "net/http"
type Error struct {
Status int `json:"status"`
Msg string `json:"msg"`
Err error `json:"err"`
Data any `json:"data"`
}
func (e *Error) Error() string {
return e.Err.Error()
}
func (e *Error) _r() *res {
data := &res{
Status: e.Status,
Msg: e.Msg,
Data: e.Data,
Err: e.Err,
}
if data.Status < 0 || data.Status > 999 {
data.Status = 500
}
return data
}
func NewError(err error, args ...any) *Error {
e := &Error{
Status: http.StatusInternalServerError,
Err: err,
}
if len(args) > 0 {
if status, ok := args[0].(int); ok {
e.Status = status
}
}
e.Msg = Msg(e.Status)
if len(args) > 1 {
if msg, ok := args[1].(string); ok {
e.Msg = msg
}
}
if len(args) > 2 {
e.Data = args[2]
}
return e
}

34
resp/msg.go Normal file
View File

@ -0,0 +1,34 @@
package resp
const (
Msg200 = "操作成功"
Msg400 = "参数错误"
Msg401 = "登录信息不存在或已过期, 请重新登录"
Msg401NoMulti = "用户已在其他地方登录"
Msg403 = "权限不足"
Msg404 = "资源不存在"
Msg500 = "服务器开小差了"
Msg501 = "服务不可用"
Msg503 = "服务不可用或正在升级, 请联系管理员"
)
func Msg(status int) string {
switch status {
case 400:
return Msg400
case 401:
return Msg401
case 403:
return Msg403
case 404:
return Msg404
case 500:
return Msg500
case 501:
return Msg501
case 503:
return Msg503
}
return "未知错误"
}

100
resp/resp.go Normal file
View File

@ -0,0 +1,100 @@
package resp
import (
"errors"
"github.com/gin-gonic/gin"
)
type res struct {
Status int `json:"status"`
Msg string `json:"msg"`
Data any `json:"data"`
Err any `json:"err"`
}
func R200(c *gin.Context, data any, msgs ...string) {
r := &res{
Status: 200,
Msg: Msg200,
Data: data,
}
if len(msgs) > 0 && msgs[0] != "" {
r.Msg = msgs[0]
}
c.AbortWithStatusJSON(200, r)
}
func RE(c *gin.Context, err error) {
var re *Error
if errors.As(err, &re) {
_r(c, re._r())
return
}
R500(c, "", nil, err)
}
func _r(c *gin.Context, r *res, args ...any) {
length := len(args)
switch length {
case 0:
break
case 1:
if msg, ok := args[0].(string); ok {
r.Msg = msg
}
case 2:
r.Data = args[1]
case 3:
r.Err = args[2]
}
if r.Msg == "" {
r.Msg = Msg(r.Status)
}
c.AbortWithStatusJSON(r.Status, r)
}
func R400(c *gin.Context, args ...any) {
r := &res{
Status: 400,
}
_r(c, r, args...)
}
func R401(c *gin.Context, args ...any) {
r := &res{
Status: 401,
}
_r(c, r, args...)
}
func R403(c *gin.Context, args ...any) {
r := &res{
Status: 403,
}
_r(c, r, args...)
}
func R500(c *gin.Context, args ...any) {
r := &res{
Status: 500,
}
_r(c, r, args...)
}
func R501(c *gin.Context, args ...any) {
r := &res{
Status: 501,
}
_r(c, r, args...)
}