router.go 28.1 KB
Newer Older
A
astaxie 已提交
1
// Copyright 2014 beego Author. All Rights Reserved.
A
astaxie 已提交
2
//
A
astaxie 已提交
3 4 5
// 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
A
astaxie 已提交
6
//
A
astaxie 已提交
7
//      http://www.apache.org/licenses/LICENSE-2.0
A
astaxie 已提交
8
//
A
astaxie 已提交
9 10 11 12 13 14
// 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.

A
fix bug  
astaxie 已提交
15 16 17
package beego

import (
J
JessonChan 已提交
18
	"errors"
A
astaxie 已提交
19
	"fmt"
A
fix bug  
astaxie 已提交
20
	"net/http"
A
astaxie 已提交
21
	"path"
A
astaxie 已提交
22
	"path/filepath"
A
fix bug  
astaxie 已提交
23
	"reflect"
A
astaxie 已提交
24
	"strconv"
A
fix bug  
astaxie 已提交
25
	"strings"
A
astaxie 已提交
26
	"sync"
27
	"time"
A
astaxie 已提交
28 29

	beecontext "github.com/astaxie/beego/context"
E
eyalpost 已提交
30
	"github.com/astaxie/beego/context/param"
31
	"github.com/astaxie/beego/logs"
A
astaxie 已提交
32
	"github.com/astaxie/beego/toolbox"
33
	"github.com/astaxie/beego/utils"
A
fix bug  
astaxie 已提交
34 35
)

A
astaxie 已提交
36
// default filter execution points
37
const (
A
astaxie 已提交
38 39
	BeforeStatic = iota
	BeforeRouter
40 41 42 43 44
	BeforeExec
	AfterExec
	FinishRouter
)

A
astaxie 已提交
45
const (
46
	routerTypeBeego = iota
A
astaxie 已提交
47 48 49 50
	routerTypeRESTFul
	routerTypeHandler
)

51
var (
A
astaxie 已提交
52
	// HTTPMETHOD list the supported http methods.
H
hao.hu 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	HTTPMETHOD = map[string]bool{
		"GET":       true,
		"POST":      true,
		"PUT":       true,
		"DELETE":    true,
		"PATCH":     true,
		"OPTIONS":   true,
		"HEAD":      true,
		"TRACE":     true,
		"CONNECT":   true,
		"MKCOL":     true,
		"COPY":      true,
		"MOVE":      true,
		"PROPFIND":  true,
		"PROPPATCH": true,
		"LOCK":      true,
		"UNLOCK":    true,
A
astaxie 已提交
70
	}
A
astaxie 已提交
71
	// these beego.Controller's methods shouldn't reflect to AutoRouter
J
JessonChan 已提交
72
	exceptMethod = []string{"Init", "Prepare", "Finish", "Render", "RenderString",
N
nemtsevp 已提交
73
		"RenderBytes", "Redirect", "Abort", "StopRun", "UrlFor", "ServeJSON", "ServeJSONP",
R
Ruben Cid 已提交
74
		"ServeYAML", "ServeXML", "Input", "ParseForm", "GetString", "GetStrings", "GetInt", "GetBool",
J
JessonChan 已提交
75 76 77
		"GetFloat", "GetFile", "SaveToFile", "StartSession", "SetSession", "GetSession",
		"DelSession", "SessionRegenerateID", "DestroySession", "IsAjax", "GetSecureCookie",
		"SetSecureCookie", "XsrfToken", "CheckXsrfCookie", "XsrfFormHtml",
N
nemtsevp 已提交
78
		"GetControllerAndAction", "ServeFormatted"}
A
astaxie 已提交
79

A
astaxie 已提交
80 81 82
	urlPlaceholder = "{{placeholder}}"
	// DefaultAccessLogFilter will skip the accesslog if return true
	DefaultAccessLogFilter FilterHandler = &logFilter{}
83
)
A
astaxie 已提交
84

A
astaxie 已提交
85
// FilterHandler is an interface for
A
astaxie 已提交
86 87 88 89 90 91 92 93 94
type FilterHandler interface {
	Filter(*beecontext.Context) bool
}

// default log filter static file will not show
type logFilter struct {
}

func (l *logFilter) Filter(ctx *beecontext.Context) bool {
A
astaxie 已提交
95
	requestPath := path.Clean(ctx.Request.URL.Path)
A
astaxie 已提交
96 97 98
	if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
		return true
	}
A
astaxie 已提交
99
	for prefix := range BConfig.WebConfig.StaticDir {
A
astaxie 已提交
100 101 102 103 104 105 106
		if strings.HasPrefix(requestPath, prefix) {
			return true
		}
	}
	return false
}

A
astaxie 已提交
107
// ExceptMethodAppend to append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
U
unphp 已提交
108 109 110 111
func ExceptMethodAppend(action string) {
	exceptMethod = append(exceptMethod, action)
}

F
Faissal Elamraoui 已提交
112 113
// ControllerInfo holds information about the controller.
type ControllerInfo struct {
114
	pattern        string
A
fix bug  
astaxie 已提交
115
	controllerType reflect.Type
A
astaxie 已提交
116
	methods        map[string]string
A
astaxie 已提交
117
	handler        http.Handler
J
JessonChan 已提交
118
	runFunction    FilterFunc
A
astaxie 已提交
119
	routerType     int
120
	initialize     func() ControllerInterface
E
eyalpost 已提交
121
	methodParams   []*param.MethodParam
A
fix bug  
astaxie 已提交
122 123
}

J
JessonChan 已提交
124 125
// ControllerRegister containers registered router rules, controller handlers and filters.
type ControllerRegister struct {
A
astaxie 已提交
126
	routers      map[string]*Tree
O
olegdemchenko 已提交
127 128
	enablePolicy bool
	policies     map[string]*Tree
A
astaxie 已提交
129
	enableFilter bool
J
JessonChan 已提交
130
	filters      [FinishRouter + 1][]*FilterRouter
A
astaxie 已提交
131
	pool         sync.Pool
A
fix bug  
astaxie 已提交
132 133
}

J
JessonChan 已提交
134 135
// NewControllerRegister returns a new ControllerRegister.
func NewControllerRegister() *ControllerRegister {
Y
Ying Zou 已提交
136
	return &ControllerRegister{
O
olegdemchenko 已提交
137 138
		routers:  make(map[string]*Tree),
		policies: make(map[string]*Tree),
Y
Ying Zou 已提交
139 140 141 142 143
		pool: sync.Pool{
			New: func() interface{} {
				return beecontext.NewContext()
			},
		},
A
astaxie 已提交
144
	}
A
fix bug  
astaxie 已提交
145 146
}

J
JessonChan 已提交
147
// Add controller handler and pattern rules to ControllerRegister.
148 149 150 151 152 153 154
// usage:
//	default methods is the same name as method
//	Add("/user",&UserController{})
//	Add("/api/list",&RestController{},"*:ListFood")
//	Add("/api/create",&RestController{},"post:CreateFood")
//	Add("/api/update",&RestController{},"put:UpdateFood")
//	Add("/api/delete",&RestController{},"delete:DeleteFood")
A
astaxie 已提交
155
//	Add("/api",&RestController{},"get,post:ApiFunc"
156
//	Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
J
JessonChan 已提交
157
func (p *ControllerRegister) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
E
eyalpost 已提交
158 159 160 161
	p.addWithMethodParams(pattern, c, nil, mappingMethods...)
}

func (p *ControllerRegister) addWithMethodParams(pattern string, c ControllerInterface, methodParams []*param.MethodParam, mappingMethods ...string) {
A
astaxie 已提交
162 163 164 165 166 167 168 169 170 171 172 173
	reflectVal := reflect.ValueOf(c)
	t := reflect.Indirect(reflectVal).Type()
	methods := make(map[string]string)
	if len(mappingMethods) > 0 {
		semi := strings.Split(mappingMethods[0], ";")
		for _, v := range semi {
			colon := strings.Split(v, ":")
			if len(colon) != 2 {
				panic("method mapping format is invalid")
			}
			comma := strings.Split(colon[0], ",")
			for _, m := range comma {
H
hao.hu 已提交
174
				if m == "*" || HTTPMETHOD[strings.ToUpper(m)] {
A
astaxie 已提交
175
					if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
A
astaxie 已提交
176
						methods[strings.ToUpper(m)] = colon[1]
A
astaxie 已提交
177
					} else {
A
astaxie 已提交
178
						panic("'" + colon[1] + "' method doesn't exist in the controller " + t.Name())
A
astaxie 已提交
179 180 181 182 183 184 185 186
					}
				} else {
					panic(v + " is an invalid method mapping. Method doesn't exist " + m)
				}
			}
		}
	}

F
Faissal Elamraoui 已提交
187
	route := &ControllerInfo{}
188
	route.pattern = pattern
A
astaxie 已提交
189 190 191
	route.methods = methods
	route.routerType = routerTypeBeego
	route.controllerType = t
192 193 194 195 196 197 198 199 200 201 202 203 204 205
	route.initialize = func() ControllerInterface {
		vc := reflect.New(route.controllerType)
		execController, ok := vc.Interface().(ControllerInterface)
		if !ok {
			panic("controller is not ControllerInterface")
		}

		elemVal := reflect.ValueOf(c).Elem()
		elemType := reflect.TypeOf(c).Elem()
		execElem := reflect.ValueOf(execController).Elem()

		numOfFields := elemVal.NumField()
		for i := 0; i < numOfFields; i++ {
			fieldType := elemType.Field(i)
206 207
			elemField := execElem.FieldByName(fieldType.Name)
			if elemField.CanSet() {
B
fix bug  
BorisBorshevsky 已提交
208
				fieldVal := elemVal.Field(i)
209
				elemField.Set(fieldVal)
B
fix bug  
BorisBorshevsky 已提交
210
			}
211 212 213 214 215
		}

		return execController
	}

E
eyalpost 已提交
216
	route.methodParams = methodParams
A
astaxie 已提交
217
	if len(methods) == 0 {
H
hao.hu 已提交
218
		for m := range HTTPMETHOD {
A
astaxie 已提交
219 220 221
			p.addToRouter(m, pattern, route)
		}
	} else {
A
astaxie 已提交
222
		for k := range methods {
A
astaxie 已提交
223
			if k == "*" {
H
hao.hu 已提交
224
				for m := range HTTPMETHOD {
A
astaxie 已提交
225 226 227 228 229 230 231 232 233
					p.addToRouter(m, pattern, route)
				}
			} else {
				p.addToRouter(k, pattern, route)
			}
		}
	}
}

F
Faissal Elamraoui 已提交
234
func (p *ControllerRegister) addToRouter(method, pattern string, r *ControllerInfo) {
A
astaxie 已提交
235
	if !BConfig.RouterCaseSensitive {
A
astaxie 已提交
236 237
		pattern = strings.ToLower(pattern)
	}
A
astaxie 已提交
238 239 240 241 242 243 244
	if t, ok := p.routers[method]; ok {
		t.AddRouter(pattern, r)
	} else {
		t := NewTree()
		t.AddRouter(pattern, r)
		p.routers[method] = t
	}
A
astaxie 已提交
245
}
A
astaxie 已提交
246

A
astaxie 已提交
247
// Include only when the Runmode is dev will generate router file in the router/auto.go from the controller
A
astaxie 已提交
248
// Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{})
J
JessonChan 已提交
249
func (p *ControllerRegister) Include(cList ...ControllerInterface) {
250
	if BConfig.RunMode == DEV {
A
astaxie 已提交
251
		skip := make(map[string]bool, 10)
A
astaxie 已提交
252 253 254
		for _, c := range cList {
			reflectVal := reflect.ValueOf(c)
			t := reflect.Indirect(reflectVal).Type()
A
astaxie 已提交
255 256
			wgopath := utils.GetGOPATHs()
			if len(wgopath) == 0 {
A
astaxie 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269
				panic("you are in dev mode. So please set gopath")
			}
			pkgpath := ""
			for _, wg := range wgopath {
				wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", t.PkgPath()))
				if utils.FileExists(wg) {
					pkgpath = wg
					break
				}
			}
			if pkgpath != "" {
				if _, ok := skip[pkgpath]; !ok {
					skip[pkgpath] = true
A
astaxie 已提交
270
					parserPkg(pkgpath, t.PkgPath())
A
astaxie 已提交
271 272 273 274 275 276 277 278 279
				}
			}
		}
	}
	for _, c := range cList {
		reflectVal := reflect.ValueOf(c)
		t := reflect.Indirect(reflectVal).Type()
		key := t.PkgPath() + ":" + t.Name()
		if comm, ok := GlobalControllerRouter[key]; ok {
A
astaxie 已提交
280
			for _, a := range comm {
281 282 283 284
				for _, f := range a.Filters {
					p.InsertFilter(f.Pattern, f.Pos, f.Filter, f.ReturnOnOutput, f.ResetParams)
				}

E
eyalpost 已提交
285
				p.addWithMethodParams(a.Router, c, a.MethodParams, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)
A
astaxie 已提交
286
			}
A
astaxie 已提交
287 288 289 290
		}
	}
}

A
astaxie 已提交
291
// Get add get method
A
astaxie 已提交
292 293 294 295
// usage:
//    Get("/", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
296
func (p *ControllerRegister) Get(pattern string, f FilterFunc) {
A
astaxie 已提交
297 298 299
	p.AddMethod("get", pattern, f)
}

A
astaxie 已提交
300
// Post add post method
A
astaxie 已提交
301 302 303 304
// usage:
//    Post("/api", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
305
func (p *ControllerRegister) Post(pattern string, f FilterFunc) {
A
astaxie 已提交
306 307 308
	p.AddMethod("post", pattern, f)
}

A
astaxie 已提交
309
// Put add put method
A
astaxie 已提交
310 311 312 313
// usage:
//    Put("/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
314
func (p *ControllerRegister) Put(pattern string, f FilterFunc) {
A
astaxie 已提交
315 316 317
	p.AddMethod("put", pattern, f)
}

A
astaxie 已提交
318
// Delete add delete method
A
astaxie 已提交
319 320 321 322
// usage:
//    Delete("/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
323
func (p *ControllerRegister) Delete(pattern string, f FilterFunc) {
A
astaxie 已提交
324 325 326
	p.AddMethod("delete", pattern, f)
}

A
astaxie 已提交
327
// Head add head method
A
astaxie 已提交
328 329 330 331
// usage:
//    Head("/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
332
func (p *ControllerRegister) Head(pattern string, f FilterFunc) {
A
astaxie 已提交
333 334 335
	p.AddMethod("head", pattern, f)
}

A
astaxie 已提交
336
// Patch add patch method
A
astaxie 已提交
337 338 339 340
// usage:
//    Patch("/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
341
func (p *ControllerRegister) Patch(pattern string, f FilterFunc) {
A
astaxie 已提交
342 343 344
	p.AddMethod("patch", pattern, f)
}

A
astaxie 已提交
345
// Options add options method
A
astaxie 已提交
346 347 348 349
// usage:
//    Options("/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
350
func (p *ControllerRegister) Options(pattern string, f FilterFunc) {
A
astaxie 已提交
351 352 353
	p.AddMethod("options", pattern, f)
}

A
astaxie 已提交
354
// Any add all method
A
astaxie 已提交
355 356 357 358
// usage:
//    Any("/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
359
func (p *ControllerRegister) Any(pattern string, f FilterFunc) {
A
astaxie 已提交
360 361 362
	p.AddMethod("*", pattern, f)
}

A
astaxie 已提交
363
// AddMethod add http method router
A
astaxie 已提交
364 365 366 367
// usage:
//    AddMethod("get","/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
J
JessonChan 已提交
368
func (p *ControllerRegister) AddMethod(method, pattern string, f FilterFunc) {
Y
DRY  
youngsterxyf 已提交
369
	method = strings.ToUpper(method)
H
hao.hu 已提交
370
	if method != "*" && !HTTPMETHOD[method] {
A
astaxie 已提交
371 372
		panic("not support http method: " + method)
	}
F
Faissal Elamraoui 已提交
373
	route := &ControllerInfo{}
374
	route.pattern = pattern
A
astaxie 已提交
375
	route.routerType = routerTypeRESTFul
J
JessonChan 已提交
376
	route.runFunction = f
A
astaxie 已提交
377 378
	methods := make(map[string]string)
	if method == "*" {
H
hao.hu 已提交
379
		for val := range HTTPMETHOD {
A
astaxie 已提交
380 381 382
			methods[val] = val
		}
	} else {
Y
DRY  
youngsterxyf 已提交
383
		methods[method] = method
A
astaxie 已提交
384 385
	}
	route.methods = methods
A
astaxie 已提交
386
	for k := range methods {
A
astaxie 已提交
387
		if k == "*" {
H
hao.hu 已提交
388
			for m := range HTTPMETHOD {
A
astaxie 已提交
389 390 391 392 393 394
				p.addToRouter(m, pattern, route)
			}
		} else {
			p.addToRouter(k, pattern, route)
		}
	}
A
astaxie 已提交
395 396
}

A
astaxie 已提交
397
// Handler add user defined Handler
J
JessonChan 已提交
398
func (p *ControllerRegister) Handler(pattern string, h http.Handler, options ...interface{}) {
F
Faissal Elamraoui 已提交
399
	route := &ControllerInfo{}
400
	route.pattern = pattern
A
astaxie 已提交
401 402
	route.routerType = routerTypeHandler
	route.handler = h
A
astaxie 已提交
403
	if len(options) > 0 {
A
astaxie 已提交
404
		if _, ok := options[0].(bool); ok {
A
astaxie 已提交
405
			pattern = path.Join(pattern, "?:all(.*)")
A
astaxie 已提交
406
		}
A
fix bug  
astaxie 已提交
407
	}
H
hao.hu 已提交
408
	for m := range HTTPMETHOD {
A
astaxie 已提交
409 410
		p.addToRouter(m, pattern, route)
	}
A
fix bug  
astaxie 已提交
411 412
}

A
astaxie 已提交
413
// AddAuto router to ControllerRegister.
414 415
// example beego.AddAuto(&MainContorlller{}),
// MainController has method List and Page.
A
astaxie 已提交
416 417
// visit the url /main/list to execute List function
// /main/page to execute Page function.
J
JessonChan 已提交
418
func (p *ControllerRegister) AddAuto(c ControllerInterface) {
A
astaxie 已提交
419
	p.AddAutoPrefix("/", c)
A
astaxie 已提交
420 421
}

A
astaxie 已提交
422
// AddAutoPrefix Add auto router to ControllerRegister with prefix.
A
astaxie 已提交
423 424 425 426
// example beego.AddAutoPrefix("/admin",&MainContorlller{}),
// MainController has method List and Page.
// visit the url /admin/main/list to execute List function
// /admin/main/page to execute Page function.
J
JessonChan 已提交
427
func (p *ControllerRegister) AddAutoPrefix(prefix string, c ControllerInterface) {
A
astaxie 已提交
428 429 430
	reflectVal := reflect.ValueOf(c)
	rt := reflectVal.Type()
	ct := reflect.Indirect(reflectVal).Type()
A
astaxie 已提交
431
	controllerName := strings.TrimSuffix(ct.Name(), "Controller")
A
astaxie 已提交
432 433
	for i := 0; i < rt.NumMethod(); i++ {
		if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
F
Faissal Elamraoui 已提交
434
			route := &ControllerInfo{}
A
astaxie 已提交
435 436 437
			route.routerType = routerTypeBeego
			route.methods = map[string]string{"*": rt.Method(i).Name}
			route.controllerType = ct
A
astaxie 已提交
438 439
			pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*")
			patternInit := path.Join(prefix, controllerName, rt.Method(i).Name, "*")
J
JessonChan 已提交
440 441
			patternFix := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name))
			patternFixInit := path.Join(prefix, controllerName, rt.Method(i).Name)
442
			route.pattern = pattern
H
hao.hu 已提交
443
			for m := range HTTPMETHOD {
A
astaxie 已提交
444
				p.addToRouter(m, pattern, route)
A
astaxie 已提交
445
				p.addToRouter(m, patternInit, route)
J
JessonChan 已提交
446 447
				p.addToRouter(m, patternFix, route)
				p.addToRouter(m, patternFixInit, route)
A
astaxie 已提交
448
			}
A
astaxie 已提交
449
		}
A
astaxie 已提交
450 451 452
	}
}

A
astaxie 已提交
453
// InsertFilter Add a FilterFunc with pattern rule and action constant.
454 455 456
// params is for:
//   1. setting the returnOnOutput value (false allows multiple filters to execute)
//   2. determining whether or not params need to be reset.
J
JessonChan 已提交
457
func (p *ControllerRegister) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error {
458 459 460 461 462 463
	mr := &FilterRouter{
		tree:           NewTree(),
		pattern:        pattern,
		filterFunc:     filter,
		returnOnOutput: true,
	}
A
astaxie 已提交
464
	if !BConfig.RouterCaseSensitive {
465
		mr.pattern = strings.ToLower(pattern)
A
astaxie 已提交
466
	}
467 468 469

	paramsLen := len(params)
	if paramsLen > 0 {
470 471
		mr.returnOnOutput = params[0]
	}
472 473 474
	if paramsLen > 1 {
		mr.resetParams = params[1]
	}
A
astaxie 已提交
475 476 477 478 479
	mr.tree.AddRouter(pattern, true)
	return p.insertFilterRouter(pos, mr)
}

// add Filter into
J
JessonChan 已提交
480 481
func (p *ControllerRegister) insertFilterRouter(pos int, mr *FilterRouter) (err error) {
	if pos < BeforeStatic || pos > FinishRouter {
J
JessonChan 已提交
482
		return errors.New("can not find your filter position")
J
JessonChan 已提交
483
	}
484
	p.enableFilter = true
J
JessonChan 已提交
485
	p.filters[pos] = append(p.filters[pos], mr)
486
	return nil
A
astaxie 已提交
487 488
}

A
astaxie 已提交
489
// URLFor does another controller handler in this request function.
490
// it can access any controller method.
A
astaxie 已提交
491
func (p *ControllerRegister) URLFor(endpoint string, values ...interface{}) string {
A
astaxie 已提交
492 493
	paths := strings.Split(endpoint, ".")
	if len(paths) <= 1 {
494
		logs.Warn("urlfor endpoint must like path.controller.method")
A
astaxie 已提交
495 496 497
		return ""
	}
	if len(values)%2 != 0 {
498
		logs.Warn("urlfor params must key-value pair")
A
astaxie 已提交
499 500
		return ""
	}
A
astaxie 已提交
501
	params := make(map[string]string)
A
astaxie 已提交
502 503 504 505
	if len(values) > 0 {
		key := ""
		for k, v := range values {
			if k%2 == 0 {
506
				key = fmt.Sprint(v)
A
astaxie 已提交
507
			} else {
508
				params[key] = fmt.Sprint(v)
A
astaxie 已提交
509 510 511
			}
		}
	}
J
JessonChan 已提交
512
	controllerName := strings.Join(paths[:len(paths)-1], "/")
A
astaxie 已提交
513
	methodName := paths[len(paths)-1]
A
astaxie 已提交
514
	for m, t := range p.routers {
J
JessonChan 已提交
515
		ok, url := p.getURL(t, "/", controllerName, methodName, params, m)
A
astaxie 已提交
516 517 518
		if ok {
			return url
		}
A
astaxie 已提交
519
	}
A
astaxie 已提交
520
	return ""
A
astaxie 已提交
521 522
}

J
JessonChan 已提交
523
func (p *ControllerRegister) getURL(t *Tree, url, controllerName, methodName string, params map[string]string, httpMethod string) (bool, string) {
A
astaxie 已提交
524 525
	for _, subtree := range t.fixrouters {
		u := path.Join(url, subtree.prefix)
J
JessonChan 已提交
526
		ok, u := p.getURL(subtree, u, controllerName, methodName, params, httpMethod)
A
astaxie 已提交
527 528 529 530 531
		if ok {
			return ok, u
		}
	}
	if t.wildcard != nil {
A
astaxie 已提交
532
		u := path.Join(url, urlPlaceholder)
J
JessonChan 已提交
533
		ok, u := p.getURL(t.wildcard, u, controllerName, methodName, params, httpMethod)
A
astaxie 已提交
534 535 536 537
		if ok {
			return ok, u
		}
	}
538
	for _, l := range t.leaves {
F
Faissal Elamraoui 已提交
539
		if c, ok := l.runObject.(*ControllerInfo); ok {
540
			if c.routerType == routerTypeBeego &&
J
JessonChan 已提交
541
				strings.HasSuffix(path.Join(c.controllerType.PkgPath(), c.controllerType.Name()), controllerName) {
A
astaxie 已提交
542
				find := false
H
hao.hu 已提交
543
				if HTTPMETHOD[strings.ToUpper(methodName)] {
A
astaxie 已提交
544 545 546
					if len(c.methods) == 0 {
						find = true
					} else if m, ok := c.methods[strings.ToUpper(methodName)]; ok && m == strings.ToUpper(methodName) {
547 548
						find = true
					} else if m, ok = c.methods["*"]; ok && m == methodName {
A
astaxie 已提交
549
						find = true
A
astaxie 已提交
550
					}
551 552
				}
				if !find {
A
astaxie 已提交
553 554
					for m, md := range c.methods {
						if (m == "*" || m == httpMethod) && md == methodName {
A
astaxie 已提交
555 556
							find = true
						}
A
astaxie 已提交
557 558
					}
				}
A
astaxie 已提交
559
				if find {
560 561
					if l.regexps == nil {
						if len(l.wildcards) == 0 {
A
astaxie 已提交
562
							return true, strings.Replace(url, "/"+urlPlaceholder, "", 1) + toURL(params)
A
astaxie 已提交
563
						}
564 565 566
						if len(l.wildcards) == 1 {
							if v, ok := params[l.wildcards[0]]; ok {
								delete(params, l.wildcards[0])
A
astaxie 已提交
567
								return true, strings.Replace(url, urlPlaceholder, v, 1) + toURL(params)
568
							}
A
astaxie 已提交
569
							return false, ""
570
						}
571
						if len(l.wildcards) == 3 && l.wildcards[0] == "." {
A
astaxie 已提交
572 573 574 575
							if p, ok := params[":path"]; ok {
								if e, isok := params[":ext"]; isok {
									delete(params, ":path")
									delete(params, ":ext")
A
astaxie 已提交
576
									return true, strings.Replace(url, urlPlaceholder, p+"."+e, -1) + toURL(params)
A
astaxie 已提交
577
								}
578
							}
A
fix #16  
astaxie 已提交
579
						}
J
JessonChan 已提交
580
						canSkip := false
581
						for _, v := range l.wildcards {
A
astaxie 已提交
582
							if v == ":" {
J
JessonChan 已提交
583
								canSkip = true
A
astaxie 已提交
584 585 586
								continue
							}
							if u, ok := params[v]; ok {
A
astaxie 已提交
587
								delete(params, v)
A
astaxie 已提交
588
								url = strings.Replace(url, urlPlaceholder, u, 1)
A
astaxie 已提交
589
							} else {
J
JessonChan 已提交
590 591
								if canSkip {
									canSkip = false
A
astaxie 已提交
592 593
									continue
								}
A
astaxie 已提交
594
								return false, ""
A
astaxie 已提交
595 596
							}
						}
A
astaxie 已提交
597
						return true, url + toURL(params)
A
astaxie 已提交
598 599
					}
					var i int
J
JessonChan 已提交
600
					var startReg bool
J
JessonChan 已提交
601
					regURL := ""
A
astaxie 已提交
602 603
					for _, v := range strings.Trim(l.regexps.String(), "^$") {
						if v == '(' {
J
JessonChan 已提交
604
							startReg = true
A
astaxie 已提交
605 606
							continue
						} else if v == ')' {
J
JessonChan 已提交
607
							startReg = false
A
astaxie 已提交
608 609
							if v, ok := params[l.wildcards[i]]; ok {
								delete(params, l.wildcards[i])
J
JessonChan 已提交
610
								regURL = regURL + v
A
astaxie 已提交
611 612 613
								i++
							} else {
								break
A
astaxie 已提交
614
							}
J
JessonChan 已提交
615
						} else if !startReg {
J
JessonChan 已提交
616
							regURL = string(append([]rune(regURL), v))
A
fix #16  
astaxie 已提交
617
						}
A
astaxie 已提交
618
					}
J
JessonChan 已提交
619 620
					if l.regexps.MatchString(regURL) {
						ps := strings.Split(regURL, "/")
A
astaxie 已提交
621 622
						for _, p := range ps {
							url = strings.Replace(url, urlPlaceholder, p, 1)
A
astaxie 已提交
623
						}
A
astaxie 已提交
624
						return true, url + toURL(params)
A
fix bug  
astaxie 已提交
625
					}
A
astaxie 已提交
626
				}
A
fix bug  
astaxie 已提交
627 628
			}
		}
A
astaxie 已提交
629
	}
630

A
astaxie 已提交
631 632 633
	return false, ""
}

J
JessonChan 已提交
634
func (p *ControllerRegister) execFilter(context *beecontext.Context, urlPath string, pos int) (started bool) {
635
	var preFilterParams map[string]string
J
JessonChan 已提交
636
	for _, filterR := range p.filters[pos] {
J
JessonChan 已提交
637 638 639
		if filterR.returnOnOutput && context.ResponseWriter.Started {
			return true
		}
640 641 642
		if filterR.resetParams {
			preFilterParams = context.Input.Params()
		}
J
JessonChan 已提交
643 644
		if ok := filterR.ValidRouter(urlPath, context); ok {
			filterR.filterFunc(context)
645 646 647 648 649 650
			if filterR.resetParams {
				context.Input.ResetParams()
				for k, v := range preFilterParams {
					context.Input.SetParam(k, v)
				}
			}
J
JessonChan 已提交
651 652 653
		}
		if filterR.returnOnOutput && context.ResponseWriter.Started {
			return true
A
astaxie 已提交
654 655 656 657 658
		}
	}
	return false
}

A
astaxie 已提交
659
// Implement http.Handler interface.
J
JessonChan 已提交
660
func (p *ControllerRegister) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
J
JessonChan 已提交
661
	startTime := time.Now()
A
astaxie 已提交
662
	var (
E
eyalpost 已提交
663 664 665 666
		runRouter    reflect.Type
		findRouter   bool
		runMethod    string
		methodParams []*param.MethodParam
667
		routerInfo   *ControllerInfo
E
eyalpost 已提交
668
		isRunnable   bool
A
astaxie 已提交
669 670
	)
	context := p.pool.Get().(*beecontext.Context)
A
astaxie 已提交
671
	context.Reset(rw, r)
672

A
astaxie 已提交
673
	defer p.pool.Put(context)
A
astaxie 已提交
674 675 676
	if BConfig.RecoverFunc != nil {
		defer BConfig.RecoverFunc(context)
	}
A
astaxie 已提交
677

A
astaxie 已提交
678
	context.Output.EnableGzip = BConfig.EnableGzip
J
JessonChan 已提交
679

680
	if BConfig.RunMode == DEV {
A
astaxie 已提交
681 682 683
		context.Output.Header("Server", BConfig.ServerName)
	}

J
JessonChan 已提交
684 685
	var urlPath = r.URL.Path

A
astaxie 已提交
686
	if !BConfig.RouterCaseSensitive {
J
JessonChan 已提交
687
		urlPath = strings.ToLower(urlPath)
A
astaxie 已提交
688
	}
689

J
JessonChan 已提交
690
	// filter wrong http method
H
hao.hu 已提交
691
	if !HTTPMETHOD[r.Method] {
692
		exception("405", context)
A
astaxie 已提交
693 694 695 696
		goto Admin
	}

	// filter for static file
J
JessonChan 已提交
697
	if len(p.filters[BeforeStatic]) > 0 && p.execFilter(context, urlPath, BeforeStatic) {
A
astaxie 已提交
698 699 700 701
		goto Admin
	}

	serverStaticRouter(context)
J
JessonChan 已提交
702

A
astaxie 已提交
703
	if context.ResponseWriter.Started {
J
JessonChan 已提交
704
		findRouter = true
A
astaxie 已提交
705 706 707
		goto Admin
	}

F
Faissal Elamraoui 已提交
708
	if r.Method != http.MethodGet && r.Method != http.MethodHead {
A
astaxie 已提交
709
		if BConfig.CopyRequestBody && !context.Input.IsUpload() {
710 711 712 713
			if r.ContentLength > BConfig.MaxMemory {
				exception("413", context)
				goto Admin
			}
A
astaxie 已提交
714 715 716 717 718
			context.Input.CopyBody(BConfig.MaxMemory)
		}
		context.Input.ParseFormOrMulitForm(BConfig.MaxMemory)
	}

A
astaxie 已提交
719
	// session init
A
astaxie 已提交
720
	if BConfig.WebConfig.Session.SessionOn {
A
astaxie 已提交
721
		var err error
A
astaxie 已提交
722
		context.Input.CruSession, err = GlobalSessions.SessionStart(rw, r)
A
astaxie 已提交
723
		if err != nil {
724
			logs.Error(err)
A
astaxie 已提交
725
			exception("503", context)
J
JessonChan 已提交
726
			goto Admin
A
astaxie 已提交
727
		}
728
		defer func() {
A
astaxie 已提交
729 730 731
			if context.Input.CruSession != nil {
				context.Input.CruSession.SessionRelease(rw)
			}
732
		}()
A
astaxie 已提交
733
	}
J
JessonChan 已提交
734
	if len(p.filters[BeforeRouter]) > 0 && p.execFilter(context, urlPath, BeforeRouter) {
735
		goto Admin
A
astaxie 已提交
736
	}
A
astaxie 已提交
737 738 739 740 741 742 743 744
	// User can define RunController and RunMethod in filter
	if context.Input.RunController != nil && context.Input.RunMethod != "" {
		findRouter = true
		runMethod = context.Input.RunMethod
		runRouter = context.Input.RunController
	} else {
		routerInfo, findRouter = p.FindRouter(context)
	}
A
fix bug  
astaxie 已提交
745

Y
ysqi 已提交
746
	//if no matches to url, throw a not found exception
J
JessonChan 已提交
747
	if !findRouter {
Y
ysqi 已提交
748 749 750 751 752 753
		exception("404", context)
		goto Admin
	}
	if splat := context.Input.Param(":splat"); splat != "" {
		for k, v := range strings.Split(splat, "/") {
			context.Input.SetParam(strconv.Itoa(k), v)
754 755 756
		}
	}

Y
ysqi 已提交
757 758
	//execute middleware filters
	if len(p.filters[BeforeExec]) > 0 && p.execFilter(context, urlPath, BeforeExec) {
759 760
		goto Admin
	}
A
fix bug  
astaxie 已提交
761

O
olegdemchenko 已提交
762 763 764 765 766
	//check policies
	if p.execPolicy(context, urlPath) {
		goto Admin
	}

Y
ysqi 已提交
767
	if routerInfo != nil {
768 769
		//store router pattern into context
		context.Input.SetData("RouterPattern", routerInfo.pattern)
Y
ysqi 已提交
770 771
		if routerInfo.routerType == routerTypeRESTFul {
			if _, ok := routerInfo.methods[r.Method]; ok {
J
JessonChan 已提交
772
				isRunnable = true
Y
ysqi 已提交
773
				routerInfo.runFunction(context)
A
astaxie 已提交
774
			} else {
Y
ysqi 已提交
775 776 777 778 779
				exception("405", context)
				goto Admin
			}
		} else if routerInfo.routerType == routerTypeHandler {
			isRunnable = true
780
			routerInfo.handler.ServeHTTP(context.ResponseWriter, context.Request)
Y
ysqi 已提交
781 782
		} else {
			runRouter = routerInfo.controllerType
E
eyalpost 已提交
783
			methodParams = routerInfo.methodParams
Y
ysqi 已提交
784
			method := r.Method
H
haley 已提交
785
			if r.Method == http.MethodPost && context.Input.Query("_method") == http.MethodPut {
F
Faissal Elamraoui 已提交
786
				method = http.MethodPut
Y
ysqi 已提交
787
			}
F
Faissal Elamraoui 已提交
788 789
			if r.Method == http.MethodPost && context.Input.Query("_method") == http.MethodDelete {
				method = http.MethodDelete
Y
ysqi 已提交
790 791 792 793 794 795 796
			}
			if m, ok := routerInfo.methods[method]; ok {
				runMethod = m
			} else if m, ok = routerInfo.methods["*"]; ok {
				runMethod = m
			} else {
				runMethod = method
A
astaxie 已提交
797
			}
798
		}
Y
ysqi 已提交
799
	}
A
fix bug  
astaxie 已提交
800

Y
ysqi 已提交
801
	// also defined runRouter & runMethod from filter
A
astaxie 已提交
802
	if !isRunnable {
Y
ysqi 已提交
803
		//Invoke the request handler
804
		var execController ControllerInterface
A
astaxie 已提交
805
		if routerInfo != nil && routerInfo.initialize != nil {
806 807 808 809 810 811 812 813
			execController = routerInfo.initialize()
		} else {
			vc := reflect.New(runRouter)
			var ok bool
			execController, ok = vc.Interface().(ControllerInterface)
			if !ok {
				panic("controller is not ControllerInterface")
			}
Y
ysqi 已提交
814
		}
A
astaxie 已提交
815

Y
ysqi 已提交
816
		//call the controller init function
817
		execController.Init(context, runRouter.Name(), runMethod, execController)
A
fix bug  
astaxie 已提交
818

Y
ysqi 已提交
819 820
		//call prepare function
		execController.Prepare()
821

Y
ysqi 已提交
822 823 824
		//if XSRF is Enable then check cookie where there has any cookie in the  request's cookie _csrf
		if BConfig.WebConfig.EnableXSRF {
			execController.XSRFToken()
F
Faissal Elamraoui 已提交
825 826
			if r.Method == http.MethodPost || r.Method == http.MethodDelete || r.Method == http.MethodPut ||
				(r.Method == http.MethodPost && (context.Input.Query("_method") == http.MethodDelete || context.Input.Query("_method") == http.MethodPut)) {
Y
ysqi 已提交
827
				execController.CheckXSRFCookie()
A
astaxie 已提交
828
			}
Y
ysqi 已提交
829
		}
A
astaxie 已提交
830

Y
ysqi 已提交
831 832 833 834 835
		execController.URLMapping()

		if !context.ResponseWriter.Started {
			//exec main logic
			switch runMethod {
F
Faissal Elamraoui 已提交
836
			case http.MethodGet:
Y
ysqi 已提交
837
				execController.Get()
F
Faissal Elamraoui 已提交
838
			case http.MethodPost:
Y
ysqi 已提交
839
				execController.Post()
F
Faissal Elamraoui 已提交
840
			case http.MethodDelete:
Y
ysqi 已提交
841
				execController.Delete()
F
Faissal Elamraoui 已提交
842
			case http.MethodPut:
Y
ysqi 已提交
843
				execController.Put()
F
Faissal Elamraoui 已提交
844
			case http.MethodHead:
Y
ysqi 已提交
845
				execController.Head()
F
Faissal Elamraoui 已提交
846
			case http.MethodPatch:
Y
ysqi 已提交
847
				execController.Patch()
F
Faissal Elamraoui 已提交
848
			case http.MethodOptions:
Y
ysqi 已提交
849
				execController.Options()
J
JessonChan 已提交
850 851
			case http.MethodTrace:
				execController.Trace()
Y
ysqi 已提交
852 853
			default:
				if !execController.HandlerFunc(runMethod) {
854
					vc := reflect.ValueOf(execController)
Y
ysqi 已提交
855
					method := vc.MethodByName(runMethod)
E
Eyal Post 已提交
856
					in := param.ConvertParams(methodParams, method.Type(), context)
E
eyalpost 已提交
857 858 859 860 861 862
					out := method.Call(in)

					//For backward compatibility we only handle response if we had incoming methodParams
					if methodParams != nil {
						p.handleParamResponse(context, execController, out)
					}
A
astaxie 已提交
863
				}
Y
ysqi 已提交
864
			}
A
astaxie 已提交
865

Y
ysqi 已提交
866 867 868 869 870
			//render template
			if !context.ResponseWriter.Started && context.Output.Status == 0 {
				if BConfig.WebConfig.AutoRender {
					if err := execController.Render(); err != nil {
						logs.Error(err)
A
astaxie 已提交
871
					}
A
fix bug  
astaxie 已提交
872 873
				}
			}
A
astaxie 已提交
874
		}
875

Y
ysqi 已提交
876 877 878 879 880 881 882
		// finish all runRouter. release resource
		execController.Finish()
	}

	//execute middleware filters
	if len(p.filters[AfterExec]) > 0 && p.execFilter(context, urlPath, AfterExec) {
		goto Admin
A
fix bug  
astaxie 已提交
883
	}
Y
ysqi 已提交
884

J
JessonChan 已提交
885
	if len(p.filters[FinishRouter]) > 0 && p.execFilter(context, urlPath, FinishRouter) {
J
JessonChan 已提交
886 887
		goto Admin
	}
A
astaxie 已提交
888

A
astaxie 已提交
889
Admin:
890
	//admin module record QPS
891 892 893 894 895 896

	statusCode := context.ResponseWriter.Status
	if statusCode == 0 {
		statusCode = 200
	}

W
Waleed Gadelkareem 已提交
897
	LogAccess(context, &startTime, statusCode)
898

899 900
	timeDur := time.Since(startTime)
	context.ResponseWriter.Elapsed = timeDur
A
astaxie 已提交
901
	if BConfig.Listen.EnableAdmin {
902 903 904 905
		pattern := ""
		if routerInfo != nil {
			pattern = routerInfo.pattern
		}
906

907
		if FilterMonitorFunc(r.Method, r.URL.Path, timeDur, pattern, statusCode) {
908
			routerName := ""
J
JessonChan 已提交
909
			if runRouter != nil {
910
				routerName = runRouter.Name()
A
astaxie 已提交
911
			}
912
			go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, routerName, timeDur)
A
astaxie 已提交
913
		}
914
	}
915

916
	if BConfig.RunMode == DEV && !BConfig.Log.AccessLogs {
917 918 919 920 921 922 923 924 925 926
		match := map[bool]string{true: "match", false: "nomatch"}
		devInfo := fmt.Sprintf("|%15s|%s %3d %s|%13s|%8s|%s %-7s %s %-3s",
			context.Input.IP(),
			logs.ColorByStatus(statusCode), statusCode, logs.ResetColor(),
			timeDur.String(),
			match[findRouter],
			logs.ColorByMethod(r.Method), r.Method, logs.ResetColor(),
			r.URL.Path)
		if routerInfo != nil {
			devInfo += fmt.Sprintf("   r:%s", routerInfo.pattern)
927
		}
928

J
JessonChan 已提交
929
		logs.Debug(devInfo)
930
	}
931 932
	// Call WriteHeader if status code has been set changed
	if context.Output.Status != 0 {
A
astaxie 已提交
933
		context.ResponseWriter.WriteHeader(context.Output.Status)
934
	}
A
fix bug  
astaxie 已提交
935 936
}

E
eyalpost 已提交
937 938 939 940
func (p *ControllerRegister) handleParamResponse(context *beecontext.Context, execController ControllerInterface, results []reflect.Value) {
	//looping in reverse order for the case when both error and value are returned and error sets the response status code
	for i := len(results) - 1; i >= 0; i-- {
		result := results[i]
E
Eyal Post 已提交
941
		if result.Kind() != reflect.Interface || !result.IsNil() {
E
eyalpost 已提交
942
			resultValue := result.Interface()
943
			context.RenderMethodResult(resultValue)
E
eyalpost 已提交
944 945
		}
	}
T
TankTheFrank 已提交
946
	if !context.ResponseWriter.Started && len(results) > 0 && context.Output.Status == 0 {
947 948
		context.Output.SetStatus(200)
	}
E
eyalpost 已提交
949 950
}

Y
ysqi 已提交
951
// FindRouter Find Router info for URL
F
Faissal Elamraoui 已提交
952
func (p *ControllerRegister) FindRouter(context *beecontext.Context) (routerInfo *ControllerInfo, isFind bool) {
Y
ysqi 已提交
953 954 955 956 957 958 959
	var urlPath = context.Input.URL()
	if !BConfig.RouterCaseSensitive {
		urlPath = strings.ToLower(urlPath)
	}
	httpMethod := context.Input.Method()
	if t, ok := p.routers[httpMethod]; ok {
		runObject := t.Match(urlPath, context)
F
Faissal Elamraoui 已提交
960
		if r, ok := runObject.(*ControllerInfo); ok {
Y
ysqi 已提交
961 962 963 964 965 966
			return r, true
		}
	}
	return
}

A
astaxie 已提交
967
func toURL(params map[string]string) string {
A
astaxie 已提交
968 969 970 971 972 973 974 975 976
	if len(params) == 0 {
		return ""
	}
	u := "?"
	for k, v := range params {
		u += k + "=" + v + "&"
	}
	return strings.TrimRight(u, "&")
}
977

978
// LogAccess logging info HTTP Access
W
Waleed Gadelkareem 已提交
979
func LogAccess(ctx *beecontext.Context, startTime *time.Time, statusCode int) {
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	//Skip logging if AccessLogs config is false
	if !BConfig.Log.AccessLogs {
		return
	}
	//Skip logging static requests unless EnableStaticLogs config is true
	if !BConfig.Log.EnableStaticLogs && DefaultAccessLogFilter.Filter(ctx) {
		return
	}
	var (
		requestTime time.Time
		elapsedTime time.Duration
		r           = ctx.Request
	)
	if startTime != nil {
		requestTime = *startTime
		elapsedTime = time.Since(*startTime)
	}
	record := &logs.AccessLogRecord{
		RemoteAddr:     ctx.Input.IP(),
		RequestTime:    requestTime,
		RequestMethod:  r.Method,
		Request:        fmt.Sprintf("%s %s %s", r.Method, r.RequestURI, r.Proto),
		ServerProtocol: r.Proto,
		Host:           r.Host,
		Status:         statusCode,
		ElapsedTime:    elapsedTime,
		HTTPReferrer:   r.Header.Get("Referer"),
		HTTPUserAgent:  r.Header.Get("User-Agent"),
		RemoteUser:     r.Header.Get("Remote-User"),
		BodyBytesSent:  0, //@todo this one is missing!
	}
	logs.AccessLog(record, BConfig.Log.AccessLogsFormat)
}