/
common.go
72 lines (56 loc) · 1.4 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package httpx
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/yeqown/cassem/pkg/errorx"
)
type ErrorCode int
const (
FAILED ErrorCode = -1
InvalidParam ErrorCode = -2
OK ErrorCode = 0
)
type CommonResponse struct {
ErrCode ErrorCode `json:"errcode"`
ErrMessage string `json:"errmsg,omitempty"`
Data interface{} `json:"data,omitempty"`
}
func responseWithStatusAndError(c *gin.Context, status int, err error, abort bool) {
if err == nil {
c.JSON(http.StatusInternalServerError, CommonResponse{
ErrCode: FAILED,
ErrMessage: "NIL ERROR, CHECK CODE PLZ",
})
return
}
var code = FAILED
if e, ok := errorx.FromError(err); ok {
code = ErrorCode(e.Code)
}
if status == 0 {
status = http.StatusBadRequest
}
c.JSON(status, CommonResponse{
ErrCode: code,
ErrMessage: err.Error(),
})
if abort {
c.Abort()
}
}
func ResponseErrorAndAbort(c *gin.Context, err error) {
responseWithStatusAndError(c, http.StatusBadRequest, err, true)
}
func ResponseError(c *gin.Context, err error) {
responseWithStatusAndError(c, http.StatusBadRequest, err, false)
}
func ResponseErrorStatusAndAbort(c *gin.Context, status int, err error) {
responseWithStatusAndError(c, status, err, true)
}
func ResponseJSON(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, CommonResponse{
ErrCode: OK,
ErrMessage: "success",
Data: data,
})
}