feat: add module resp
This commit is contained in:
100
resp/resp.go
Normal file
100
resp/resp.go
Normal 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...)
|
||||
}
|
Reference in New Issue
Block a user