-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
348 lines (283 loc) · 9.36 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2013 slowfei And The Contributors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Create on 2013-8-16
// Update on 2014-07-17
// Email slowfei#foxmail.com
// Home http://www.slowfei.com
//
// controller handle
//
package leafveingo
import (
"bytes"
"fmt"
"github.com/slowfei/gosfcore/encoding/json"
"github.com/slowfei/gosfcore/utils/filemanager"
"github.com/slowfei/leafveingo/template"
"net/http"
"path"
"reflect"
"time"
)
var (
// controller reflect type
RefTypeBeforeAfterController = reflect.TypeOf((*BeforeAfterController)(nil)).Elem()
RefTypeAdeRouterController = reflect.TypeOf((*AdeRouterController)(nil)).Elem()
)
//#pragma mark interface option ----------------------------------------------------------------------------------------------------
type ControllerOption struct {
scheme URIScheme // the support scheme URI_SCHEME_HTTPS || URI_SCHEME_HTTP
host string // "svn.slowfei.com" || "wwww.slowfei.com" || "slowfei.com" || ""(wildcard)
}
/**
* get sheme
*
* @return
*/
func (c ControllerOption) Scheme() URIScheme {
return c.scheme
}
/**
* set the support scheme
*
* URI_SCHEME_HTTPS | URI_SCHEME_HTTP
*/
func (c *ControllerOption) SetScheme(scheme URIScheme) {
c.scheme = scheme
}
/**
* get host
*
* @return
*/
func (c ControllerOption) Host() string {
return c.host
}
/**
* set host
* "svn.slowfei.com" || "wwww.slowfei.com" || ""(wildcard)
*/
func (c *ControllerOption) SetHost(host string) {
c.host = host
}
/**
* checked params
*/
func (c *ControllerOption) Checked() {
}
//
// before after interface
//
type BeforeAfterController interface {
/**
* before the call controller func
*
* @param context
* @param option
* @return Status200 pass, StatusNil stop Next to proceed, other status jump relevant status page
*
*/
Before(context *HttpContext, option *RouterOption) HttpStatus
/**
* after the call controller func
*
* @param context
* @param option
*/
After(context *HttpContext, option *RouterOption)
}
//
// 高级路由器控制器接口,实现高级路由器机制的控制器需要实现该接口
// 特别注意,指针添加控制器和值添加的控制器的实现区别
// 指针控制器的实现: func (c *XxxController) RouterMethodParse...
// 值控制器的实现:func (c XxxController) RouterMethodParse...
//
type AdeRouterController interface {
/**
* 路由函数解析,解析工作完全交由现实对象进行。
*
* @param option router params option
* @return funcName is "" jump 404 page, other by name call controller
* @return params add to request form param, use set Request.URL.Query()
*/
RouterMethodParse(option *RouterOption) (funcName string, params map[string]string)
}
//#pragma mark Leafveingo method ----------------------------------------------------------------------------------------------------
/**
* controller call handle
*
* @param context
* @param router router interface implement object
* @param option router params option
* @param funcName controller call func name
* @param isDisp is Dispatcher
* @param dispFunaName no dispatcher to nil
* @param logBuf log info buffer
* @return statusCode
* @return err
*/
func controllerCallHandle(context *HttpContext, router IRouter, option *RouterOption, isDisp bool, dispFunaName string, logBuf *bytes.Buffer) (statusCode HttpStatus, err error) {
var funcName string = ""
var returnValue interface{} = nil
// parse func name
dispstr := ""
if isDisp {
dispstr = "(dispatcher)"
funcName = dispFunaName
statusCode = Status200
err = nil
} else {
funcName, statusCode, err = router.ParseFuncName(context, option)
}
// parse form params
paramErr := context.parseForm()
timeNow := time.Now()
if nil == paramErr {
fmt.Fprintf(logBuf, "[%d.%d]request fileNum: %d; params: %v \n", timeNow.Second(), timeNow.Nanosecond(), len(context.formparams.files), context.formparams.params)
} else {
fmt.Fprintf(logBuf, "[%d.%d]request params(error): %s \n", timeNow.Second(), timeNow.Nanosecond(), paramErr.Error())
}
// controller info
fmt.Fprintf(logBuf, "[%d.%d]func name: [\"%s\"] controller info%s: %s \n", timeNow.Second(), timeNow.Nanosecond(), funcName, dispstr, router.Info())
if Status200 != statusCode || nil != err {
return
}
context.routerKeys = append(context.routerKeys, option.RouterKey)
context.funcNames = append(context.funcNames, funcName)
// before
statusCode = router.CallFuncBefore(context, option)
if Status200 == statusCode {
// exce call
returnValue, statusCode, err = router.CallFunc(context, funcName, option)
if Status200 == statusCode && nil == err {
if nil != returnValue {
// return value handle
statusCode, err = controllerReturnValueHandle(returnValue, context, router, option, funcName, logBuf)
}
}
}
// after
router.CallFuncAfter(context, option)
return
}
/**
* controller return value handle
*
* @param returnValue body return value
* @param context leafvein http context
* @param router router interface
* @param option router option
* @param funcName request call controller func name
* @param logBuf log info buffer
* @return statusCode http status code
* @return err error info
*/
func controllerReturnValueHandle(returnValue interface{}, context *HttpContext, router IRouter, option *RouterOption, funcName string, logBuf *bytes.Buffer) (statusCode HttpStatus, err error) {
statusCode = Status200
lv := context.lvServer
switch cvt := returnValue.(type) {
case string:
context.RespWrite.Header().Set("Content-Type", "text/plain; charset="+lv.Charset())
context.RespBodyWrite([]byte(cvt), Status200)
case ByteOut:
if 0 == len(cvt.ContentType) {
context.RespWrite.Header().Set("Content-Type", "text/plain; charset="+lv.Charset())
} else {
context.RespWrite.Header().Set("Content-Type", cvt.ContentType)
}
for k, v := range cvt.Headers {
context.RespWrite.Header().Set(k, v)
}
context.RespBodyWrite(cvt.Body, Status200)
case SFJson.Json:
context.RespWrite.Header().Set("Content-Type", "application/json; charset="+lv.Charset())
context.RespBodyWrite(cvt.Bytes(), Status200)
case HtmlOut:
context.RespWrite.Header().Set("Content-Type", "text/html; charset="+lv.Charset())
context.RespBodyWrite([]byte(cvt), Status200)
case HttpStatusValue:
err := context.StatusPageWriteByValue(cvt)
if nil != err {
lv.log.Debug(err.Error())
}
case LVTemplate.TemplateValue:
contentType := cvt.ContentType
if 0 != len(contentType) {
context.RespWrite.Header().Set("Content-Type", contentType)
} else {
context.RespWrite.Header().Set("Content-Type", "text/html; charset="+lv.Charset())
}
tplPath := cvt.TplPath
tplName := cvt.TplName
if 0 == len(tplPath) && 0 == len(tplName) {
cvt.TplPath = router.ParseTemplatePath(context, funcName, option)
if 0 == len(cvt.TplPath) {
statusCode = Status500
panic(ErrTemplatePathParseNil)
}
}
fmt.Fprintf(logBuf, "access template path: \"%s\"", cvt.TplPath)
e := lv.template.Execute(context.ComperssWriter(), cvt)
if nil != e {
statusCode = Status500
panic(NewLeafveinError("template: " + e.Error()))
}
case Redirect:
context.RespWrite.Header().Del("Content-Encoding")
http.Redirect(context.RespWrite, context.Request, cvt.URLPath, int(cvt.Code))
statusCode = cvt.Code
case Dispatcher:
if 0 == len(cvt.FuncName) {
statusCode = Status500
panic(ErrControllerDispatcherFuncNameNil)
}
if router, ok := context.routerElement.routers[cvt.RouterKey]; ok {
// request的一些设置由调用者直接进行设置Header
for k, v := range cvt.Headers {
context.Request.Header.Set(k, v)
}
// TODO 这样转发可能存在隐藏性的问题,关键在于option的作用。但目前的代码设计来说还不存在大的问题。
option.RouterKey = cvt.RouterKey
option.RouterPath = ""
statusCode, err = controllerCallHandle(context, router, option, true, cvt.FuncName, logBuf)
} else {
statusCode = Status500
// 这个是自定义写代码的转发,如果查找不到相当于是调用者代码问题,所以直接抛出异常(恐慌)。
dnfErr := *ErrControllerDispatcherNotFound
dnfErr.UserInfo = "host:" + context.routerElement.host + "; router key:" + cvt.RouterKey
panic(&dnfErr)
}
case ServeFilePath:
statusCode = Status404
filePath := string(cvt)
if 0 != len(filePath) {
jsonChrt := ""
if '/' != filePath[0] {
jsonChrt = "/"
}
context.RespWrite.Header().Del("Content-Encoding")
fullPath := lv.WebRootDir() + jsonChrt + filePath
if isExists, isDir, _ := SFFileManager.Exists(fullPath); isExists && !isDir {
statusCode = Status200
_, fileName := path.Split(filePath)
context.RespWrite.Header().Set("Content-Disposition", "attachment;filename=\""+fileName+"\"")
http.ServeFile(context.RespWrite, context.Request, fullPath)
}
}
default:
panic(ErrControllerReturnParam)
}
return
}