-
Notifications
You must be signed in to change notification settings - Fork 5
/
router.go
303 lines (247 loc) · 7.27 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
package pgo2
import (
"reflect"
"regexp"
"strings"
"github.com/pinguo/pgo2/core"
"github.com/pinguo/pgo2/iface"
"github.com/pinguo/pgo2/util"
)
// format route string to CamelCase, eg.
// /api/foo-bar/say-hello => /Api/FooBar/SayHello
func routeFormatFunc(s string) string {
s = strings.ToUpper(s)
if s[0] == '-' {
s = s[1:]
}
return s
}
// format route string to CamelCase, eg.
// /path/FooBar/SayHello => /api/foo-bar/say-hello
func pathFormatFunc(s string) string {
s = strings.ToLower(s)
return "-" + s
}
type routeRule struct {
rePat *regexp.Regexp
pattern string
route string
}
// Router the router component, configuration:
// router:
// httpStatus:true // Whether to override the HTTP status code
// rules:
// - "^/foo/all$ => /foo/index"
// - "^/api/user/(\d+)$ => /api/user"
func NewRouter(config map[string]interface{}) *Router {
router := &Router{}
router.reFmt = regexp.MustCompile(`([/-][a-z])`)
router.rePathFmt = regexp.MustCompile(`([A-Z])`)
router.rules = make([]routeRule, 0, 10)
core.Configure(router, config)
return router
}
type Handler struct {
uri string
cPath string
cId string
aName string
aId int
}
type Router struct {
reFmt *regexp.Regexp
rePathFmt *regexp.Regexp
rules []routeRule
webHandlers map[string]*Handler
cmdHandlers map[string]*Handler
modules []string
errorController string
httpStatus bool // Whether to override the HTTP status code
}
var rePath = strings.NewReplacer("/"+ControllerCmdPkg+"/", "/", "/"+ControllerWebPkg+"/", "/", ControllerCmdType, "", ControllerWebType, "")
func (r *Router) SetHttpStatus(v bool) {
r.httpStatus = v
}
func (r *Router) SetErrorController(v string) {
r.errorController = v
}
// SetRules set rule list, format: `^/api/user/(\d+)$ => /api/user`
func (r *Router) SetRules(rules []interface{}) {
for _, v := range rules {
parts := strings.Split(v.(string), "=>")
if len(parts) != 2 {
panic("Router: invalid rule: " + util.ToString(v))
}
pattern := strings.TrimSpace(parts[0])
route := strings.TrimSpace(parts[1])
r.AddRoute(pattern, route)
}
}
// InitHandlers Initialization route
func (r *Router) InitHandlers() {
r.webHandlers = make(map[string]*Handler)
r.cmdHandlers = make(map[string]*Handler)
webList := App().Container().PathList(ControllerWebPkg+"/", ControllerWebType)
cmdList := App().Container().PathList(ControllerCmdPkg+"/", ControllerCmdType)
r.SetHandlers(ControllerWebPkg, webList)
r.SetHandlers(ControllerCmdPkg, cmdList)
}
// SetHandlers Set route
func (r *Router) SetHandlers(cmdType string, list map[string]interface{}) {
if list == nil {
return
}
for controllerOPath, info := range list {
actions, _ := info.(map[string]int)
controllerPath := rePath.Replace("/" + controllerOPath)
paths := strings.Split(controllerPath, "/")
oCname := paths[len(paths)-1:][0]
cName := r.firstToLower(oCname)
baseUrl := strings.Join(paths[0:len(paths)-1], "/") + "/"
baseUrl = strings.Replace(baseUrl, "//", "/", -1)
cNames := make([]string, 0, 2)
cNames = append(cNames, cName)
if r.web(cmdType) {
fmtCName := r.rePathFmt.ReplaceAllStringFunc(cName, pathFormatFunc)
if cName != fmtCName {
cNames = append(cNames, fmtCName)
}
}
for oAName, aNum := range actions {
aNames := make([]string, 0, 2)
aName := oAName
restFul, _ := restFulActions[oAName]
if restFul != 1 {
aName = r.firstToLower(oAName)
}
aNames = append(aNames, aName)
if restFul != 1 && r.web(cmdType) {
fmtAName := r.rePathFmt.ReplaceAllStringFunc(aName, pathFormatFunc)
if aName != fmtAName {
aNames = append(aNames, fmtAName)
}
}
for _, cPath := range cNames {
for _, aPath := range aNames {
uri := baseUrl + cPath + "/" + aPath
r.setHandler(cmdType, uri, controllerOPath, baseUrl+cPath, oAName, aNum)
if aName == DefaultActionPath && r.web(cmdType) {
uri := baseUrl + cPath
r.setHandler(cmdType, uri, controllerOPath, baseUrl+cPath, oAName, aNum)
}
}
}
}
}
}
func (r *Router) web(cmdType string) bool {
return cmdType == ControllerWebPkg
}
func (r *Router) firstToLower(s string) string {
return strings.ToLower(s[0:1]) + s[1:]
}
func (r *Router) setHandler(cmdType, uri, cPath, cId, aName string, aNum int) {
switch cmdType {
case ControllerWebPkg:
uri = strings.ToLower(uri)
r.webHandlers[uri] = &Handler{uri: uri, cPath: cPath, cId: cId, aName: aName, aId: aNum}
case ControllerCmdPkg:
r.cmdHandlers[uri] = &Handler{uri: uri, cPath: cPath, cId: cId, aName: aName, aId: aNum}
default:
panic("Is the defined cmdType")
}
}
// AddRoute add one route, the captured group will be passed to
// action method as function params
func (r *Router) AddRoute(pattern, route string) {
rePat := regexp.MustCompile(pattern)
rule := routeRule{rePat, pattern, route}
r.rules = append(r.rules, rule)
}
// Resolve path to route and action params, then format route to CamelCase
func (r *Router) Resolve(path, method string) (handler *Handler, params []string) {
// The first mapping
handler = r.Handler(path)
if handler != nil {
return
}
restFulSuffix := ""
// format path
if path == "/" {
path += DefaultControllerPath + "/" + DefaultActionPath
} else {
restFulSuffix = "/" + method
path += restFulSuffix
//if r.modules != nil && util.SliceSearchString(r.modules, path) > 0 {
// path += "/" + DefaultControllerPath + "/" + DefaultActionPath
//}
}
path = util.CleanPath(path)
// The second mapping
handler = r.Handler(path)
if handler != nil {
return
}
if restFulSuffix != "" {
path = strings.Replace(path, restFulSuffix, "", 1)
}
// Custom route
if len(r.rules) != 0 {
for _, rule := range r.rules {
matches := rule.rePat.FindStringSubmatch(path)
if len(matches) != 0 {
path = rule.route
params = matches[1:]
break
}
}
}
handler = r.Handler(path)
return
}
func (r *Router) Handler(path string) *Handler {
if ModeWeb == App().mode {
path = strings.ToLower(path)
if handler, ok := r.webHandlers[path]; ok {
return handler
}
return nil
}
if handler, ok := r.cmdHandlers[path]; ok {
return handler
}
path = strings.ToLower(path)
for kPath, handler := range r.cmdHandlers {
if strings.ToLower(kPath) == path {
return handler
}
}
return nil
}
func (r *Router) CmdHandlers() map[string]*Handler {
return r.cmdHandlers
}
// CreateController Create the controller and parameters
func (r *Router) CreateController(path string, ctx iface.IContext) (reflect.Value, reflect.Value, []string) {
container := App().Container()
handler, params := r.Resolve(path, ctx.Method())
if handler == nil {
return reflect.Value{}, reflect.Value{}, nil
}
controllerName := handler.cPath
ctx.SetControllerId(handler.cId)
ctx.SetActionId(handler.aName)
controllerName = GetAlias(controllerName)
controller := container.Get(controllerName, ctx)
action := controller.Method(handler.aId)
return controller, action, params
}
func (r *Router) ErrorController(ctx iface.IContext, statuses ...int) iface.IController {
if r.httpStatus && len(statuses) > 0 && statuses[0] > 0 && ModeWeb == App().mode {
ctx.Output().WriteHeader(statuses[0])
}
container := App().Container()
controllerName := GetAlias(r.errorController)
controller := container.Get(controllerName, ctx)
return controller.Interface().(iface.IController)
}