selfcheer
2024-07-19 1572f45e72cc0fa15c029f9ee2a08474104435e6
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
73
74
75
76
77
78
79
80
81
82
package utils
 
import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
    "srm/utils/code"
)
 
type Response struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}
 
type ResponseList struct {
    Code     int         `json:"code"`
    Msg      string      `json:"msg"`
    Data     interface{} `json:"data"`
    Total    int         `json:"total"`
    Page     int         `json:"page"`
    PageSize int         `json:"pageSize"`
}
 
// ResponseFormat 返回数据格式化
func ResponseFormat(c *gin.Context, respStatus *code.Code, data interface{}) {
    if respStatus == nil {
        respStatus = code.RequestParamError
    }
    if respStatus.Status != http.StatusOK {
        c.JSON(http.StatusOK, Response{
            respStatus.Status,
            fmt.Sprintf("%v", data),
            nil,
        })
    } else {
        c.JSON(http.StatusOK, Response{
            respStatus.Status,
            respStatus.Message,
            data,
        })
    }
}
 
// ResponseFail 失败返回
func ResponseFail(c *gin.Context, respStatus *code.Code) {
    if respStatus == nil {
        respStatus = code.RequestParamError
    }
    c.JSON(http.StatusOK, Response{
        respStatus.Status,
        respStatus.Message,
        nil,
    })
}
 
// ResponseFormatList 返回包含总数的列表
func ResponseFormatList(c *gin.Context, respStatus *code.Code, data interface{}, count int) {
    if respStatus == nil {
        respStatus = code.RequestParamError
    }
    c.JSON(http.StatusOK, ResponseList{
        Code:  respStatus.Status,
        Msg:   respStatus.Message,
        Data:  data,
        Total: count,
    })
}
 
func ResponseFormatListWithPage(c *gin.Context, respStatus *code.Code, data interface{}, count int, page, pageSize int) {
    if respStatus == nil {
        respStatus = code.RequestParamError
    }
    c.JSON(respStatus.Status, ResponseList{
        Code:     respStatus.Status,
        Msg:      respStatus.Message,
        Data:     data,
        Total:    count,
        Page:     page,
        PageSize: pageSize,
    })
}