-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
53 lines (45 loc) · 1.21 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
package gintool
import (
"github.com/gin-gonic/gin"
)
type CommonResponse struct {
RequestID string `json:"request_id,omitempty"`
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
func RespOK(id string, code int, data interface{}) *CommonResponse {
return &CommonResponse{
RequestID: id,
Code: code,
Message: CodeMsg(code),
Data: data,
}
}
func RespError(id string, code int, err error) *CommonResponse {
resp := &CommonResponse{
RequestID: id,
Code: code,
Message: CodeMsg(code),
}
if err != nil {
resp.Message += " - " + err.Error()
}
return resp
}
func FinishWithCodeData(c *gin.Context, code int, data interface{}) {
c.JSON(HTTPStatus(code), RespOK(GetRequestID(c), code, data))
}
func AbortWithCodeErr(c *gin.Context, code int, err error) {
c.AbortWithStatusJSON(HTTPStatus(code), RespError(GetRequestID(c), code, err))
}
func GetCommonFinisher() HandlerFunc {
return func(c *gin.Context, gc *Context) {
FinishWithCodeData(c, gc.GetCode(), gc.GetData())
}
}
func GetCommonAborter() HandlerFunc {
return func(c *gin.Context, gc *Context) {
AbortWithCodeErr(c, gc.GetCode(), gc.GetError())
}
}