-
Notifications
You must be signed in to change notification settings - Fork 188
/
app.go
55 lines (46 loc) · 1018 Bytes
/
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
55
package app
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-programming-tour-book/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,
}
}
func (r *Response) ToResponse(data interface{}) {
if data == nil {
data = gin.H{}
}
r.Ctx.JSON(http.StatusOK, data)
}
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,
},
})
}
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)
}