Files
packages/resp/resp.go
2025-07-14 11:16:34 +08:00

136 lines
1.7 KiB
Go

package resp
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
)
type res struct {
Status int `json:"status"`
Msg string `json:"msg"`
Data any `json:"data"`
Err any `json:"err"`
// Deprecated: 200:1, other: -1
Code int `json:"code"`
}
func R200(c *gin.Context, data any, msgs ...string) {
r := &res{
Status: 200,
Msg: Msg200,
Data: data,
Code: 1,
}
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)
if length == 0 {
goto END
}
if length >= 4 {
goto H4
}
if length >= 3 {
goto H3
}
if length >= 2 {
goto H2
}
if length >= 1 {
goto H1
}
H4:
if code, err := cast.ToIntE(args[3]); err == nil {
r.Code = code
}
H3:
if es, ok := args[2].(error); ok {
r.Err = es.Error()
} else {
r.Err = args[2]
}
H2:
r.Data = args[1]
H1:
if msg, ok := args[0].(string); ok {
r.Msg = msg
}
END:
if r.Msg == "" {
r.Msg = Msg(r.Status)
}
c.AbortWithStatusJSON(r.Status, r)
}
func R400(c *gin.Context, args ...any) {
r := &res{
Status: 400,
Code: -1,
}
_r(c, r, args...)
}
func R401(c *gin.Context, args ...any) {
r := &res{
Status: 401,
Code: -1,
}
_r(c, r, args...)
}
func R403(c *gin.Context, args ...any) {
r := &res{
Status: 403,
Code: -1,
}
_r(c, r, args...)
}
func R500(c *gin.Context, args ...any) {
r := &res{
Status: 500,
Code: -1,
}
_r(c, r, args...)
}
func R501(c *gin.Context, args ...any) {
r := &res{
Status: 501,
Code: -1,
}
_r(c, r, args...)
}