-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
54 lines (44 loc) · 1.04 KB
/
app.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
package app
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/pudongping/gin-blog-service/pkg/errcode"
)
type Response struct {
Ctx *gin.Context
}
type Pager struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalRows int `json:"total_rows"`
}
func NewResponse(ctx *gin.Context) *Response {
return &Response{Ctx: ctx}
}
// ToResponse 正确数据返回
func (r *Response) ToResponse(data interface{}) {
if data == nil {
data = gin.H{}
}
r.Ctx.JSON(http.StatusOK, data)
}
// ToResponseList 分页数据返回
func (r *Response) ToResponseList(list interface{}, totalRows int) {
r.Ctx.JSON(http.StatusOK, gin.H{
"list": list,
"pager": Pager{
Page: GetPage(r.Ctx),
PageSize: GetPageSize(r.Ctx),
TotalRows: totalRows,
},
})
}
// ToErrorResponse 错误返回
func (r *Response) ToErrorResponse(err *errcode.Error) {
response := gin.H{"code": err.Code(), "msg": err.Msg()}
details := err.Details()
if len(details) > 0 {
response["details"] = details
}
r.Ctx.JSON(err.StatusCode(), response)
}