-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
389 lines (322 loc) · 8.81 KB
/
router.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// 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-9-14
// Update on 2014-07-17
// Email slowfei#foxmail.com
// Home http://www.slowfei.com
//
// router manager
//
package leafveingo
import (
// "github.com/slowfei/gosfcore/debug"
"fmt"
"github.com/slowfei/gosfcore/utils/strings"
"net/http"
"reflect"
)
var (
// globalRouterList
_globalRouterList []globalRouter = nil
)
//#pragma mark global handle ----------------------------------------------------------------------------------------------------
//
// global router
//
type globalRouter struct {
appName string
router IRouter
}
/**
* global add router
*
* @param appName
* @param routerKey
* @param router
*/
func AddRouter(appName string, router IRouter) {
_globalRouterList = append(_globalRouterList, globalRouter{appName, router})
}
//#pragma mark interface option ----------------------------------------------------------------------------------------------------
//
// router element
//
type RouterElement struct {
host string
routerKeys []string
routers map[string]IRouter
}
//
// router option
//
type RouterOption struct {
/*
GET http://localhost:8080/home/index.go
routerKey = "/home/"
routerPath = "index"
requestMethod = "get"
urlSuffix = "go"
GET http://localhost:8080/home/manager/help.go
routerKey = "/home/"
routerPath = "manager/help"
requestMethod = "get"
urlSuffix = "go"
GET http://localhost:8080/home/manager/other
routerKey = "/home/"
routerPath = "manager/other"
requestMethod = "get"
urlSuffix = ""
GET http://localhost:8080/home#!other
routerKey = "/home"
routerPath = "#!other"
requestMethod = "get"
urlSuffix = ""
*/
RouterData interface{} // custom storage data
RouterDataRefVal reflect.Value // reflect value data
RouterKey string //
RouterPath string // have been converted to lowercase
RequestMethod string // lowercase get post ...
UrlSuffix string // lowercase
AppName string // application name
}
//
// router interface
//
type IRouter interface {
/**
* 1. after router parse
*
* @param context
* @param option
* @return HttpStatus 200 pass
*/
AfterRouterParse(context *HttpContext, option *RouterOption) HttpStatus
/**
* 2. parse func name
*
* @param context http context
* @param option router option
* @return funcName function name specifies call
* @return statusCode http status code, 200 pass, other to status page
*/
ParseFuncName(context *HttpContext, option *RouterOption) (funcName string, statusCode HttpStatus, err error)
/**
* 3. before call func
*
* @param context
* @param option
* @return HttpStatus
*/
CallFuncBefore(context *HttpContext, option *RouterOption) HttpStatus
/**
* 4. request func
*
* @param context http content
* @param funcName call controller func name
* @param option router option
* @return returnValue controller func return value
* @return statusCode http status code, 200 pass, other to status page
*/
CallFunc(context *HttpContext, funcName string, option *RouterOption) (returnValue interface{}, statusCode HttpStatus, err error)
/**
* 5. parse template path
* no need to add the suffix
*
* @param context
* @param funcName controller call func name
* @param option router option
* @return template path, suggest "[routerKey]/[funcName]"
*/
ParseTemplatePath(context *HttpContext, funcName string, option *RouterOption) string
/**
* 6. after call func
*
* @param context
* @param option
*/
CallFuncAfter(context *HttpContext, option *RouterOption)
/**
* @return router key
*/
RouterKey() string
/**
* @return controller option
*/
ControllerOption() ControllerOption
/**
* @return controller info
*/
Info() string
}
//#pragma mark Leafveingo method ----------------------------------------------------------------------------------------------------
/**
* router parse
*
* @param context
* @param reqPathNoSuffix the no suffix request path
* @param reqSuffix url request suffix
*/
func routerParse(context *HttpContext, reqPathNoSuffix, reqSuffix string) (router IRouter, option *RouterOption, statusCode HttpStatus) {
statusCode = Status404
var lowerReqPath string
if context.lvServer.IsReqPathIgnoreCase() {
lowerReqPath = SFStringsUtil.ToLower(reqPathNoSuffix)
} else {
lowerReqPath = reqPathNoSuffix
}
reqPathLen := len(lowerReqPath)
// FOR routerList -> IF host -> IF scheme -> FOR keys -> IF reqPath
listCount := len(context.lvServer.routerList)
for i := 0; i < listCount; i++ {
element := context.lvServer.routerList[i]
if context.reqHost == element.host {
keyCount := len(element.routerKeys)
for j := 0; j < keyCount; j++ {
key := element.routerKeys[j]
keyLen := len(key)
if keyLen <= reqPathLen && key == lowerReqPath[:keyLen] {
// controller router find
if iR, ok := element.routers[key]; ok {
// uri scheme handle
statusCode = routerSchemeHandle(context, iR.ControllerOption().Scheme())
if statusCode != Status200 {
router = nil
option = nil
return
}
context.routerElement = element
router = iR
option = new(RouterOption)
option.AppName = context.lvServer.AppName()
if 0 != len(reqSuffix) {
if '.' == reqSuffix[0] {
reqSuffix = reqSuffix[1:]
}
option.UrlSuffix = SFStringsUtil.ToLower(reqSuffix)
}
option.RequestMethod = SFStringsUtil.ToLower(context.Request.Method)
if 0 == len(option.RequestMethod) {
option.RequestMethod = "get"
}
option.RouterKey = key
option.RouterPath = lowerReqPath[keyLen:]
statusCode = router.AfterRouterParse(context, option)
} else {
// 基本上不会进来此处
context.lvServer.log.Error("lv.routerKeys contains %#v and lv.routers not contains %#v", key, key)
statusCode = Status404
}
return
} // end keyLen <= reqPathLen && key == lowerReqPath[:keyLen]
} // end j := 0; j < keyCount; j++
} // end context.reqHost == element.host
} // end i := 0; i < listCount; i++
return
}
/**
* router uri scheme handle
*
* @param context
* @param scheme
* @return statusCode Status200 pass
*/
func routerSchemeHandle(context *HttpContext, scheme URIScheme) (statusCode HttpStatus) {
statusCode = Status400
switch context.RequestScheme() {
case URI_SCHEME_HTTP:
if scheme&URI_SCHEME_HTTP == URI_SCHEME_HTTP {
statusCode = Status200
break
}
// TODO 下一步考虑委托函数处理不支持的协议,可让用户来处理。
if scheme&URI_SCHEME_HTTPS == URI_SCHEME_HTTPS {
if "GET" == context.Request.Method {
// 重定向操作
statusCode = StatusNil
routerSchemeRedirect(context, URI_SCHEME_HTTPS)
}
}
case URI_SCHEME_HTTPS:
if scheme&URI_SCHEME_HTTPS == URI_SCHEME_HTTPS {
statusCode = Status200
break
}
if scheme&URI_SCHEME_HTTP == URI_SCHEME_HTTP {
if "GET" == context.Request.Method {
// 重定向操作
statusCode = StatusNil
routerSchemeRedirect(context, URI_SCHEME_HTTP)
}
}
default:
}
return
}
/**
* does not support the scheme redirect handle
*
* @param context
* @param scheme
*/
func routerSchemeRedirect(context *HttpContext, scheme URIScheme) {
schemeStr := ""
port := 0
switch scheme {
case URI_SCHEME_HTTP:
schemeStr = "http://"
port = context.lvServer.port
case URI_SCHEME_HTTPS:
if nil == context.lvServer.tlsListener {
return
}
schemeStr = "https://"
port = context.lvServer.tlsPort
default:
return
}
// host
host := context.Request.Host
hostLen := len(host)
// remove port
retScope := hostLen - 7
if 0 > retScope {
retScope = 0
}
index := -1
for i := hostLen - 1; i >= retScope; i-- {
if ':' == host[i] {
index = i
break
}
}
if -1 != index {
host = fmt.Sprintf("%s:%d", host[:index], port)
}
// path
path := context.Request.URL.Path
if 0 == len(path) {
path = "/"
} else if '/' != path[0] {
path = "/" + path
}
query := context.Request.URL.Query().Encode()
if 0 != len(query) {
query = "?" + query
}
urlstr := schemeStr + host + path + query
http.Redirect(context.RespWrite, context.Request, urlstr, int(Status302))
context.LVServer().Log().Debug("scheme redirect to: " + urlstr)
}