-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdata_json.go
executable file
·136 lines (114 loc) · 2.32 KB
/
data_json.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
基于 context 的扩展方法
处理了:
1. 自定义JSON输出格式;
2. 常用的翻页处理;
sam
2021/6/7
*/
package gow
import "time"
// DataResponse data struct
type DataResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Time int `json:"time"`
Body *Body `json:"body"`
}
// Body struct
type Body struct {
Pager *Pager `json:"pager"`
Data interface{} `json:"data"`
}
// Pager pager struct
type Pager struct {
Page int64 `json:"page"`
Limit int64 `json:"-"`
Offset int64 `json:"-"`
Count int64 `json:"count"`
PageCount int64 `json:"page_count"`
}
// DataPager middleware
// r.Use(gow.DataPager())
// like : /v1/user/page?page=1&limit=20
func DataPager() HandlerFunc {
return func(c *Context) {
pager := &Pager{}
pager.Page, _ = c.GetInt64("page", 1)
if pager.Page < 1 {
pager.Page = 1
}
pager.Limit, _ = c.GetInt64("limit", 10)
if pager.Limit < 1 {
pager.Limit = 1
}
pager.Offset = (pager.Page - 1) * pager.Limit
c.Pager = pager
c.Next()
}
}
// ServerDataJSON response JSON format
// statusCode httpStatusCode
// like: c.ServerDataJSON(401,1,"UnAuthorized")
func (c *Context) ServerDataJSON(statusCode int, args ...interface{}) {
var (
err error
pager *Pager
data interface{}
msg string
code int
)
for _, v := range args {
switch vv := v.(type) {
case int:
code = vv
case string:
msg = vv
case error:
err = vv
case *Pager:
pager = vv
default:
data = vv
}
}
if err != nil {
debugPrint("[error]", c.Request.URL.String(), err.Error())
}
if code == 0 && msg == "" {
msg = "success"
}
body := new(Body)
if pager != nil {
pager.PageCount = getPageCount(pager.Count, pager.Limit)
} else {
pager = &Pager{}
}
body.Pager = pager
body.Data = data
resp := &DataResponse{
Code: code,
Msg: msg,
Time: int(time.Now().Unix()),
Body: body,
}
c.ServerJSON(statusCode, &resp)
return
}
// DataJSON response JSON format
// c.DataJSON(1,"lost param")
// c.DataJSON()
func (c *Context) DataJSON(args ...interface{}) {
c.ServerDataJSON(200, args...)
}
// getPageCount return pagerCount
func getPageCount(count, limit int64) (pageCount int64) {
if count > 0 && limit > 0 {
if count%limit == 0 {
pageCount = count / limit
} else {
pageCount = (count / limit) + 1
}
}
return pageCount
}