-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
321 lines (287 loc) · 6.83 KB
/
controller.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package core
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/grestful/logs"
"github.com/grestful/utils"
"net/http"
"strings"
"time"
)
type Context struct {
*gin.Context
}
type ProcessFunc func(controller *Controller) IError
type Controller struct {
//log trackId
TrackId string //访问id
//the gin context
Ctx *Context
//response code, default success
Code string
//controller error
error IError
//response data
Data interface{} //output from data raw data parse
Req interface{} //input params
// middleware functions
Middleware []ProcessFunc
// logic functions
ProcessFun ProcessFunc
}
//func Session(controller *Controller) error {
// typ := gGore.GetSessionType()
//
// sid := ""
// cookName, err := gGore.Config.GetValue("", "SESSION_NAME")
// if cookName == "" {
// cookName = "sid"
// }
// cook, err := controller.GetContext().Request.Cookie(cookName)
// if err != nil {
// return err
// }
// if cook.Value == "" {
// sid = controller.GetContext().Request.URL.Query().Get(cookName)
// } else {
// sid = cook.Value
// }
//
// if sid == "" {
// return errors.New("sid is empty")
// }
//
// maxLeftStr, err := gGore.Config.GetValue("session", "max_left_time")
// if err != nil || maxLeftStr == "" {
// maxLeftStr = "3600"
// }
// maxLeft := utils.String2Int64(maxLeftStr, 3600)
// switch typ {
// case SessionTypeFile:
// path, err := gGore.Config.GetValue("session", "file_path")
// if err != nil || path == "" {
// path = "/tmp"
// }
//
// sess := session.GetNewFileSession(path, maxLeft)
// controller.Session = session.GetNewUserSession(sid, sess)
// return nil
// case SessionTypeRedis:
// name, err := gGore.Config.GetValue("session", "redis_name")
// if err != nil || name == "" {
// name = "default"
// }
// c := gGore.GetRedis(name)
// if c == nil {
// return errors.New(fmt.Sprintf("can't find redis connection name %s", name))
// }
// maxLeft := utils.String2Int64(maxLeftStr, 3600)
// sess := session.GetNewRedisSession(c, maxLeft)
// controller.Session = session.GetNewUserSession(sid, sess)
// return nil
// }
//
// return errors.New("session type error")
//}
// get new Controller
// demo:
// c := GetNewController(g, &UserInfo{UserId:1})
// c.ProcessFunc = func(con *Controller) IError {
// u := con.Req.(*Req)
// con.Data = u
// }
func GetNewController(g *gin.Context, req interface{}) *Controller {
return &Controller{
Ctx: &Context{
Context: g,
},
Code: SuccessCode,
Req: req,
}
}
//alias name, If run it, do not use RunProcess
func RunWithRequest(req interface{}, g *gin.Context) {
ct := GetNewController(g, req)
c := GetContext(g)
var e IError
defer func() {
if x := recover(); x != nil {
logs.Error(" panic :", x)
e = Error{
Code: "500",
Msg: "运行时内部错误",
Err: x,
}
}
if e != nil {
ct.SetError(e)
}
var err error
c.Status(200)
c.Header("Content-Type", "application/json; charset=utf-8")
defer func() {
if err != nil {
errStr := fmt.Sprintf(`{"code":"%s","msg":"system error: %s","data":null}`, FailInternal, err.Error())
rStr(c, errStr)
}
}()
res := ct.getResponse()
rJson(c, res)
}()
if e = getTrackId(ct); e != nil {
return
}
if e = runProcess(ct); e != nil {
return
}
}
//run
func RunProcess(controller IController, g *gin.Context) {
c := GetContext(g)
controller.SetContext(c)
var e IError
defer func() {
if x := recover(); x != nil {
logs.Error(" panic :", x)
e = Error{
Code: "500",
Msg: "运行时内部错误",
Err: x,
}
}
if e != nil {
controller.SetError(e)
}
var err error
c.Status(200)
c.Header("Content-Type", "application/json; charset=utf-8")
defer func() {
if err != nil {
errStr := fmt.Sprintf(`{"code":"%s","msg":"system error: %s","data":null}`, FailInternal, err.Error())
rStr(c, errStr)
}
}()
res := controller.getResponse()
rJson(c, res)
}()
if e = getTrackId(controller); e != nil {
return
}
if e = runProcess(controller); e != nil {
return
}
}
func getTrackId(controller IController) IError {
trackId := utils.GetRequestKey(controller.GetContext().Request, "track_id")
if trackId == "" {
//return NewErrorStr("need params track_id")
trackId = utils.Int642String(time.Now().Unix() * 1000)
}
controller.SetTrackId(trackId)
return nil
}
//run controller process
func runProcess(controller IController) (err IError) {
err = controller.Decode()
if err != nil {
//controller.SetError(err)
return
}
err = controller.Process()
if err != nil {
return
}
return
}
func (controller *Controller) Use(fn func(controller *Controller) IError) {
if controller.Middleware == nil {
controller.Middleware = make([]ProcessFunc, 1)
}
controller.Middleware = append(controller.Middleware, fn)
}
// controller default Decode
func (controller *Controller) Decode() IError {
controller.Data = nil
switch controller.Ctx.Context.Request.Method {
case http.MethodPost:
fallthrough
case http.MethodPut:
fallthrough
case http.MethodDelete:
ct := controller.Ctx.Context.Request.Header.Get("Content-Type")
if strings.Contains(ct, "json") {
bt, err := controller.Ctx.GetRawData()
if err == nil {
if len(bt) == 0 {
bt = []byte("{}")
}
d := json.NewDecoder(bytes.NewReader(bt))
d.UseNumber()
if err := d.Decode(&controller.Req); err != nil {
return NewErrorCode(FailJsonParse)
}
}
}
default:
}
return nil
}
// controller default Process
func (controller *Controller) Process() IError {
if controller.Middleware != nil {
if len(controller.Middleware) > 0 {
for _, m := range controller.Middleware {
err := m(controller)
if err != nil {
return err
}
}
}
}
if controller.ProcessFun != nil {
return controller.ProcessFun(controller)
}
return nil
}
//ger ready response
func (controller *Controller) getResponse() Response {
if controller.error != nil {
return getDefaultErrorResponse(controller.error)
} else {
return getResponseWithCode(controller.Code, controller.Data)
}
}
//set error
func (controller *Controller) SetError(err IError) {
logs.Info("set error in %s, track_id: %s, err: %s\n", controller.Ctx.Context.Request.URL.Path, controller.GetTrackId(), err.GetMsg())
controller.error = err
return
}
//get trackId
func (controller *Controller) GetTrackId() string {
return controller.TrackId
}
//set trackId
func (controller *Controller) SetTrackId(id string) {
controller.TrackId = id
}
//set Context
func (controller *Controller) SetContext(c *Context) {
if controller.Ctx == nil {
controller.Ctx = c
}
}
//get gin Content
func (controller *Controller) GetContext() *Context {
return controller.Ctx
}
//query things with gin
func (controller *Controller) Query(key string) string {
return controller.Ctx.Query(key)
}
//router params with gin
func (controller *Controller) Param(key string) string {
return controller.Ctx.Param(key)
}