router.go 21.7 KB
Newer Older
A
fix bug  
astaxie 已提交
1 2 3
package beego

import (
A
astaxie 已提交
4
	"fmt"
A
fix bug  
astaxie 已提交
5 6
	"net/http"
	"net/url"
A
fix #81  
astaxie 已提交
7
	"os"
A
fix bug  
astaxie 已提交
8 9 10
	"reflect"
	"regexp"
	"runtime"
A
astaxie 已提交
11
	"strconv"
A
fix bug  
astaxie 已提交
12
	"strings"
13
	"time"
A
astaxie 已提交
14 15 16 17

	beecontext "github.com/astaxie/beego/context"
	"github.com/astaxie/beego/middleware"
	"github.com/astaxie/beego/toolbox"
18
	"github.com/astaxie/beego/utils"
A
fix bug  
astaxie 已提交
19 20
)

21 22 23 24 25 26 27 28
const (
	BeforeRouter = iota
	AfterStatic
	BeforeExec
	AfterExec
	FinishRouter
)

29 30 31
var (
	HTTPMETHOD = []string{"get", "post", "put", "delete", "patch", "options", "head"}
)
A
astaxie 已提交
32

A
fix bug  
astaxie 已提交
33 34 35 36 37
type controllerInfo struct {
	pattern        string
	regex          *regexp.Regexp
	params         map[int]string
	controllerType reflect.Type
A
astaxie 已提交
38
	methods        map[string]string
A
astaxie 已提交
39
	hasMethod      bool
A
fix bug  
astaxie 已提交
40 41 42
}

type ControllerRegistor struct {
43 44
	routers       []*controllerInfo // regexp router storage
	fixrouters    []*controllerInfo // fixed router storage
A
astaxie 已提交
45 46 47 48
	enableFilter  bool
	filters       map[int][]*FilterRouter
	enableAuto    bool
	autoRouter    map[string]map[string]reflect.Type //key:controller key:method value:reflect.type
49
	contextBuffer chan *beecontext.Context           //context buffer pool
A
fix bug  
astaxie 已提交
50 51 52
}

func NewControllerRegistor() *ControllerRegistor {
A
astaxie 已提交
53
	return &ControllerRegistor{
A
astaxie 已提交
54 55 56
		routers:       make([]*controllerInfo, 0),
		autoRouter:    make(map[string]map[string]reflect.Type),
		filters:       make(map[int][]*FilterRouter),
57
		contextBuffer: make(chan *beecontext.Context, 1000),
A
astaxie 已提交
58
	}
A
fix bug  
astaxie 已提交
59 60
}

A
astaxie 已提交
61 62 63 64 65 66 67 68 69 70
//methods support like this:
//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")
//Add("/api",&RestController{},"get,post:ApiFunc")
//Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
A
fix bug  
astaxie 已提交
71 72 73 74 75 76
	parts := strings.Split(pattern, "/")

	j := 0
	params := make(map[int]string)
	for i, part := range parts {
		if strings.HasPrefix(part, ":") {
A
astaxie 已提交
77
			expr := "(.+)"
A
fix bug  
astaxie 已提交
78
			//a user may choose to override the defult expression
79
			// similar to expressjs: ‘/user/:id([0-9]+)’
A
fix bug  
astaxie 已提交
80 81 82
			if index := strings.Index(part, "("); index != -1 {
				expr = part[index:]
				part = part[:index]
A
astaxie 已提交
83
				//match /user/:id:int ([0-9]+)
A
astaxie 已提交
84
				//match /post/:username:string	([\w]+)
A
astaxie 已提交
85 86
			} else if lindex := strings.LastIndex(part, ":"); lindex != 0 {
				switch part[lindex:] {
A
astaxie 已提交
87
				case ":int":
A
astaxie 已提交
88
					expr = "([0-9]+)"
A
astaxie 已提交
89
					part = part[:lindex]
A
astaxie 已提交
90
				case ":string":
A
astaxie 已提交
91
					expr = `([\w]+)`
A
astaxie 已提交
92
					part = part[:lindex]
A
astaxie 已提交
93
				}
A
fix bug  
astaxie 已提交
94 95 96 97 98
			}
			params[j] = part
			parts[i] = expr
			j++
		}
A
astaxie 已提交
99 100 101 102
		if strings.HasPrefix(part, "*") {
			expr := "(.+)"
			if part == "*.*" {
				params[j] = ":path"
A
astaxie 已提交
103
				parts[i] = "([^.]+).([^.]+)"
A
astaxie 已提交
104 105 106 107 108 109 110 111 112
				j++
				params[j] = ":ext"
				j++
			} else {
				params[j] = ":splat"
				parts[i] = expr
				j++
			}
		}
A
astaxie 已提交
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
		//url like someprefix:id(xxx).html
		if strings.Contains(part, ":") && strings.Contains(part, "(") && strings.Contains(part, ")") {
			var out []rune
			var start bool
			var startexp bool
			var param []rune
			var expt []rune
			for _, v := range part {
				if start {
					if v != '(' {
						param = append(param, v)
						continue
					}
				}
				if startexp {
					if v != ')' {
						expt = append(expt, v)
						continue
					}
				}
				if v == ':' {
					param = make([]rune, 0)
					param = append(param, ':')
					start = true
				} else if v == '(' {
					startexp = true
					start = false
					params[j] = string(param)
					j++
					expt = make([]rune, 0)
					expt = append(expt, '(')
				} else if v == ')' {
					startexp = false
					expt = append(expt, ')')
					out = append(out, expt...)
				} else {
					out = append(out, v)
				}
			}
			parts[i] = string(out)
		}
A
fix bug  
astaxie 已提交
154
	}
A
astaxie 已提交
155 156
	reflectVal := reflect.ValueOf(c)
	t := reflect.Indirect(reflectVal).Type()
A
astaxie 已提交
157 158 159 160 161 162
	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 {
V
vadimi 已提交
163
				panic("method mapping format is invalid")
A
astaxie 已提交
164 165 166
			}
			comma := strings.Split(colon[0], ",")
			for _, m := range comma {
167
				if m == "*" || utils.InSlice(strings.ToLower(m), HTTPMETHOD) {
A
astaxie 已提交
168
					if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
A
astaxie 已提交
169 170
						methods[strings.ToLower(m)] = colon[1]
					} else {
V
vadimi 已提交
171
						panic(colon[1] + " method doesn't exist in the controller " + t.Name())
A
astaxie 已提交
172 173
					}
				} else {
V
vadimi 已提交
174
					panic(v + " is an invalid method mapping. Method doesn't exist " + m)
A
astaxie 已提交
175 176 177 178
				}
			}
		}
	}
A
fix bug  
astaxie 已提交
179 180 181 182 183
	if j == 0 {
		//now create the Route
		route := &controllerInfo{}
		route.pattern = pattern
		route.controllerType = t
A
astaxie 已提交
184
		route.methods = methods
A
astaxie 已提交
185 186 187
		if len(methods) > 0 {
			route.hasMethod = true
		}
A
fix bug  
astaxie 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200
		p.fixrouters = append(p.fixrouters, route)
	} else { // add regexp routers
		//recreate the url pattern, with parameters replaced
		//by regular expressions. then compile the regex
		pattern = strings.Join(parts, "/")
		regex, regexErr := regexp.Compile(pattern)
		if regexErr != nil {
			//TODO add error handling here to avoid panic
			panic(regexErr)
			return
		}

		//now create the Route
A
astaxie 已提交
201

A
fix bug  
astaxie 已提交
202 203 204 205
		route := &controllerInfo{}
		route.regex = regex
		route.params = params
		route.pattern = pattern
A
astaxie 已提交
206
		route.methods = methods
A
astaxie 已提交
207 208 209
		if len(methods) > 0 {
			route.hasMethod = true
		}
A
fix bug  
astaxie 已提交
210 211 212 213 214
		route.controllerType = t
		p.routers = append(p.routers, route)
	}
}

215
// add auto router to controller
216 217 218 219
// example beego.AddAuto(&MainContorlller{})
// MainController has method List and Page
// you can visit the url /main/list to exec List function
// /main/page to exec Page function
A
astaxie 已提交
220
func (p *ControllerRegistor) AddAuto(c ControllerInterface) {
A
astaxie 已提交
221
	p.enableAuto = true
A
astaxie 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235
	reflectVal := reflect.ValueOf(c)
	rt := reflectVal.Type()
	ct := reflect.Indirect(reflectVal).Type()
	firstParam := strings.ToLower(strings.TrimSuffix(ct.Name(), "Controller"))
	if _, ok := p.autoRouter[firstParam]; ok {
		return
	} else {
		p.autoRouter[firstParam] = make(map[string]reflect.Type)
	}
	for i := 0; i < rt.NumMethod(); i++ {
		p.autoRouter[firstParam][rt.Method(i).Name] = ct
	}
}

236 237 238
func (p *ControllerRegistor) AddFilter(pattern, action string, filter FilterFunc) {
	mr := buildFilter(pattern, filter)
	switch action {
A
astaxie 已提交
239
	case "BeforeRouter":
240 241 242 243 244 245 246 247 248 249 250 251 252
		p.filters[BeforeRouter] = append(p.filters[BeforeRouter], mr)
	case "AfterStatic":
		p.filters[AfterStatic] = append(p.filters[AfterStatic], mr)
	case "BeforeExec":
		p.filters[BeforeExec] = append(p.filters[BeforeExec], mr)
	case "AfterExec":
		p.filters[AfterExec] = append(p.filters[AfterExec], mr)
	case "FinishRouter":
		p.filters[FinishRouter] = append(p.filters[FinishRouter], mr)
	}
	p.enableFilter = true
}

K
knightmare 已提交
253
func (p *ControllerRegistor) InsertFilter(pattern string, pos int, filter FilterFunc) {
254
	mr := buildFilter(pattern, filter)
K
knightmare 已提交
255
	p.filters[pos] = append(p.filters[pos], mr)
256
	p.enableFilter = true
A
astaxie 已提交
257 258
}

A
astaxie 已提交
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
func (p *ControllerRegistor) UrlFor(endpoint string, values ...string) string {
	paths := strings.Split(endpoint, ".")
	if len(paths) <= 1 {
		Warn("urlfor endpoint must like path.controller.method")
		return ""
	}
	if len(values)%2 != 0 {
		Warn("urlfor params must key-value pair")
		return ""
	}
	urlv := url.Values{}
	if len(values) > 0 {
		key := ""
		for k, v := range values {
			if k%2 == 0 {
				key = v
			} else {
				urlv.Set(key, v)
			}
		}
	}
	controllName := strings.Join(paths[:len(paths)-1], ".")
	methodName := paths[len(paths)-1]
	for _, route := range p.fixrouters {
		if route.controllerType.Name() == controllName {
			var finded bool
285
			if utils.InSlice(strings.ToLower(methodName), HTTPMETHOD) {
A
astaxie 已提交
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
				if route.hasMethod {
					if m, ok := route.methods[strings.ToLower(methodName)]; ok && m != methodName {
						finded = false
					} else if m, ok = route.methods["*"]; ok && m != methodName {
						finded = false
					} else {
						finded = true
					}
				} else {
					finded = true
				}
			} else if route.hasMethod {
				for _, md := range route.methods {
					if md == methodName {
						finded = true
					}
				}
			}
			if !finded {
				continue
			}
			if len(values) > 0 {
				return route.pattern + "?" + urlv.Encode()
			}
			return route.pattern
		}
	}
	for _, route := range p.routers {
		if route.controllerType.Name() == controllName {
			var finded bool
316
			if utils.InSlice(strings.ToLower(methodName), HTTPMETHOD) {
A
astaxie 已提交
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
				if route.hasMethod {
					if m, ok := route.methods[strings.ToLower(methodName)]; ok && m != methodName {
						finded = false
					} else if m, ok = route.methods["*"]; ok && m != methodName {
						finded = false
					} else {
						finded = true
					}
				} else {
					finded = true
				}
			} else if route.hasMethod {
				for _, md := range route.methods {
					if md == methodName {
						finded = true
					}
				}
			}
			if !finded {
				continue
			}
			var returnurl string
			var i int
			var startreg bool
			for _, v := range route.regex.String() {
				if v == '(' {
					startreg = true
					continue
				} else if v == ')' {
					startreg = false
					returnurl = returnurl + urlv.Get(route.params[i])
					i++
				} else if !startreg {
					returnurl = string(append([]rune(returnurl), v))
				}
			}
			if route.regex.MatchString(returnurl) {
				return returnurl
			}
		}
	}
	if p.enableAuto {
		for cName, methodList := range p.autoRouter {
			if strings.ToLower(strings.TrimSuffix(paths[len(paths)-2], "Controller")) == cName {
				if _, ok := methodList[methodName]; ok {
					if len(values) > 0 {
						return "/" + strings.TrimSuffix(paths[len(paths)-2], "Controller") + "/" + methodName + "?" + urlv.Encode()
					} else {
						return "/" + strings.TrimSuffix(paths[len(paths)-2], "Controller") + "/" + methodName
					}
				}
			}
		}
	}
	return ""
}

374
// main function to serveHTTP
A
fix bug  
astaxie 已提交
375 376 377
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
A
astaxie 已提交
378
			if err == USERSTOPRUN {
A
astaxie 已提交
379 380
				return
			}
381 382
			if _, ok := err.(middleware.HTTPException); ok {
				// catch intented errors, only for HTTP 4XX and 5XX
A
fix bug  
astaxie 已提交
383
			} else {
A
astaxie 已提交
384
				if RunMode == "dev" {
385 386 387
					if !RecoverPanic {
						panic(err)
					} else {
388 389 390 391 392 393
						if ErrorsShow {
							if handler, ok := middleware.ErrorMaps[fmt.Sprint(err)]; ok {
								handler(rw, r)
								return
							}
						}
394 395 396 397 398 399 400 401
						var stack string
						Critical("Handler crashed with error", err)
						for i := 1; ; i++ {
							_, file, line, ok := runtime.Caller(i)
							if !ok {
								break
							}
							Critical(file, line)
A
astaxie 已提交
402
							stack = stack + fmt.Sprintln(file, line)
A
fix #16  
astaxie 已提交
403
						}
A
astaxie 已提交
404 405 406
						middleware.ShowErr(err, rw, r, stack)
					}
				} else {
407 408
					if !RecoverPanic {
						panic(err)
A
astaxie 已提交
409
					} else {
410 411 412 413
						// in production model show all infomation
						if ErrorsShow {
							handler := p.getErrorHandler(fmt.Sprint(err))
							handler(rw, r)
414
							return
A
astaxie 已提交
415 416 417 418 419 420 421 422 423
						} else {
							Critical("Handler crashed with error", err)
							for i := 1; ; i++ {
								_, file, line, ok := runtime.Caller(i)
								if !ok {
									break
								}
								Critical(file, line)
							}
A
fix #16  
astaxie 已提交
424
						}
A
fix bug  
astaxie 已提交
425
					}
A
astaxie 已提交
426
				}
A
astaxie 已提交
427

A
fix bug  
astaxie 已提交
428 429 430
			}
		}
	}()
A
astaxie 已提交
431

432 433
	starttime := time.Now()
	requestPath := r.URL.Path
434
	var runrouter reflect.Type
435
	var findrouter bool
436
	var runMethod string
437 438
	params := make(map[string]string)

A
fix bug  
astaxie 已提交
439
	w := &responseWriter{writer: rw}
A
astaxie 已提交
440
	w.Header().Set("Server", BeegoServerName)
A
astaxie 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

	// init context
	var context *beecontext.Context
	select {
	case context = <-p.contextBuffer:
		context.ResponseWriter = w
		context.Request = r
		context.Input.Request = r
	default:
		context = &beecontext.Context{
			ResponseWriter: w,
			Request:        r,
			Input:          beecontext.NewInput(r),
			Output:         beecontext.NewOutput(),
		}
		context.Output.Context = context
		context.Output.EnableGzip = EnableGzip
A
astaxie 已提交
458
	}
A
astaxie 已提交
459

A
astaxie 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473
	defer func() {
		if context != nil {
			select {
			case p.contextBuffer <- context:
			default:
			}
		}
	}()

	if context.Input.IsWebsocket() {
		context.ResponseWriter = rw
	}

	// defined filter function
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
	do_filter := func(pos int) (started bool) {
		if p.enableFilter {
			if l, ok := p.filters[pos]; ok {
				for _, filterR := range l {
					if ok, p := filterR.ValidRouter(r.URL.Path); ok {
						context.Input.Params = p
						filterR.filterFunc(context)
						if w.started {
							return true
						}
					}
				}
			}
		}

489
		return false
490 491
	}

A
astaxie 已提交
492 493 494 495 496 497
	// session init
	if SessionOn {
		context.Input.CruSession = GlobalSessions.SessionStart(w, r)
		defer context.Input.CruSession.SessionRelease()
	}

498
	if !utils.InSlice(strings.ToLower(r.Method), HTTPMETHOD) {
A
astaxie 已提交
499
		http.Error(w, "Method Not Allowed", 405)
500
		goto Admin
A
astaxie 已提交
501 502
	}

503 504
	if do_filter(BeforeRouter) {
		goto Admin
A
astaxie 已提交
505 506
	}

A
fix bug  
astaxie 已提交
507 508
	//static file server
	for prefix, staticDir := range StaticDir {
509 510 511 512
		if r.URL.Path == "/favicon.ico" {
			file := staticDir + r.URL.Path
			http.ServeFile(w, r, file)
			w.started = true
513
			goto Admin
514
		}
A
fix bug  
astaxie 已提交
515 516
		if strings.HasPrefix(r.URL.Path, prefix) {
			file := staticDir + r.URL.Path[len(prefix):]
A
fix #81  
astaxie 已提交
517 518
			finfo, err := os.Stat(file)
			if err != nil {
519 520 521
				if RunMode == "dev" {
					Warn(err)
				}
A
astaxie 已提交
522
				http.NotFound(w, r)
523
				goto Admin
A
fix #81  
astaxie 已提交
524 525 526
			}
			//if the request is dir and DirectoryIndex is false then
			if finfo.IsDir() && !DirectoryIndex {
A
astaxie 已提交
527
				middleware.Exception("403", rw, r, "403 Forbidden")
528
				goto Admin
A
fix #81  
astaxie 已提交
529
			}
530

F
Francois 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
			//This block obtained from (https://github.com/smithfox/beego) - it should probably get merged into astaxie/beego after a pull request
			isStaticFileToCompress := false
			if StaticExtensionsToGzip != nil && len(StaticExtensionsToGzip) > 0 {
				for _, statExtension := range StaticExtensionsToGzip {
					if strings.HasSuffix(strings.ToLower(file), strings.ToLower(statExtension)) {
						isStaticFileToCompress = true
						break
					}
				}
			}

			if isStaticFileToCompress {
				if EnableGzip {
					w.contentEncoding = GetAcceptEncodingZip(r)
				}

				memzipfile, err := OpenMemZipFile(file, w.contentEncoding)
				if err != nil {
					return
				}

				w.InitHeadContent(finfo.Size())

				http.ServeContent(w, r, file, finfo.ModTime(), memzipfile)
			} else {
				http.ServeFile(w, r, file)
			}
558

A
fix bug  
astaxie 已提交
559
			w.started = true
560
			goto Admin
A
fix bug  
astaxie 已提交
561 562 563
		}
	}

564 565
	if do_filter(AfterStatic) {
		goto Admin
A
astaxie 已提交
566
	}
A
fix bug  
astaxie 已提交
567

A
astaxie 已提交
568
	if CopyRequestBody {
A
astaxie 已提交
569
		context.Input.Body()
A
astaxie 已提交
570 571
	}

A
fix bug  
astaxie 已提交
572 573 574
	//first find path from the fixrouters to Improve Performance
	for _, route := range p.fixrouters {
		n := len(requestPath)
A
astaxie 已提交
575
		if requestPath == route.pattern {
576
			runrouter = route.controllerType
A
astaxie 已提交
577
			findrouter = true
578
			runMethod = p.getRunMethod(r.Method, context.Input.Query("_method"), route)
A
astaxie 已提交
579
			break
580
		}
A
astaxie 已提交
581 582 583
		// pattern /admin   url /admin 200  /admin/ 404
		// pattern /admin/  url /admin 301  /admin/ 200
		if requestPath[n-1] != '/' && len(route.pattern) == n+1 &&
A
astaxie 已提交
584
			route.pattern[n] == '/' && route.pattern[:n] == requestPath {
A
astaxie 已提交
585
			http.Redirect(w, r, requestPath+"/", 301)
586
			goto Admin
A
fix bug  
astaxie 已提交
587 588 589
		}
	}

A
astaxie 已提交
590
	//find regex's router
A
fix bug  
astaxie 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
	if !findrouter {
		//find a matching Route
		for _, route := range p.routers {

			//check if Route pattern matches url
			if !route.regex.MatchString(requestPath) {
				continue
			}

			//get submatches (params)
			matches := route.regex.FindStringSubmatch(requestPath)

			//double check that the Route matches the URL pattern.
			if len(matches[0]) != len(requestPath) {
				continue
			}

			if len(route.params) > 0 {
				//add url parameters to the query param map
				values := r.URL.Query()
				for i, match := range matches[1:] {
					values.Add(route.params[i], match)
					params[route.params[i]] = match
				}
				//reassemble query params and add to RawQuery
A
astaxie 已提交
616
				r.URL.RawQuery = url.Values(values).Encode()
A
fix bug  
astaxie 已提交
617
			}
618
			runrouter = route.controllerType
A
fix bug  
astaxie 已提交
619
			findrouter = true
620
			context.Input.Params = params
621
			runMethod = p.getRunMethod(r.Method, context.Input.Query("_method"), route)
A
fix bug  
astaxie 已提交
622 623 624
			break
		}
	}
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
	if !findrouter && p.enableAuto {
		// deal with url with diffirent ext
		// /controller/simple
		// /controller/simple.html
		// /controller/simple.json
		// /controller/simple.rss
		lastindex := strings.LastIndex(requestPath, "/")
		lastsub := requestPath[lastindex+1:]
		if subindex := strings.LastIndex(lastsub, "."); subindex != -1 {
			context.Input.Params[":ext"] = lastsub[subindex+1:]
			r.URL.Query().Add(":ext", lastsub[subindex+1:])
			r.URL.RawQuery = r.URL.Query().Encode()
			requestPath = requestPath[:len(requestPath)-len(lastsub[subindex:])]
		}
		for cName, methodmap := range p.autoRouter {
			// if prev already find the router break
			if findrouter {
				break
			}
			if strings.ToLower(requestPath) == "/"+cName {
				http.Redirect(w, r, requestPath+"/", 301)
				goto Admin
			}
			// if there's no action, set the default action to index
			if strings.ToLower(requestPath) == "/"+cName+"/" {
				requestPath = requestPath + "index"
			}
			// if the request path start with controllerName
			if strings.HasPrefix(strings.ToLower(requestPath), "/"+cName+"/") {
				for mName, controllerType := range methodmap {
					if strings.ToLower(requestPath) == "/"+cName+"/"+strings.ToLower(mName) ||
						(strings.HasPrefix(strings.ToLower(requestPath), "/"+cName+"/"+strings.ToLower(mName)) &&
							requestPath[len("/"+cName+"/"+strings.ToLower(mName)):len("/"+cName+"/"+strings.ToLower(mName))+1] == "/") {
						runrouter = controllerType
						runMethod = mName
						findrouter = true
A
astaxie 已提交
662 663 664 665 666 667 668 669
						//parse params
						otherurl := requestPath[len("/"+cName+"/"+strings.ToLower(mName)):]
						if len(otherurl) > 1 {
							plist := strings.Split(otherurl, "/")
							for k, v := range plist[1:] {
								context.Input.Params[strconv.Itoa(k)] = v
							}
						}
670 671 672 673 674 675 676 677 678 679 680 681
						break
					}
				}
			}
		}
	}

	//if no matches to url, throw a not found exception
	if !findrouter {
		middleware.Exception("404", rw, r, "")
		goto Admin
	}
A
fix bug  
astaxie 已提交
682

683
	if findrouter {
A
astaxie 已提交
684 685 686
		if r.Method == "POST" {
			r.ParseMultipartForm(MaxMemory)
		}
A
fix bug  
astaxie 已提交
687
		//execute middleware filters
688 689
		if do_filter(BeforeExec) {
			goto Admin
A
fix bug  
astaxie 已提交
690
		}
691

A
fix bug  
astaxie 已提交
692
		//Invoke the request handler
693
		vc := reflect.New(runrouter)
694 695 696 697
		execController, ok := vc.Interface().(ControllerInterface)
		if !ok {
			panic("controller is not ControllerInterface")
		}
A
fix bug  
astaxie 已提交
698 699

		//call the controller init function
700
		execController.Init(context, runrouter.Name(), runMethod, vc.Interface())
A
fix bug  
astaxie 已提交
701

A
astaxie 已提交
702 703
		//if XSRF is Enable then check cookie where there has any cookie in the  request's cookie _csrf
		if EnableXSRF {
704
			execController.XsrfToken()
A
astaxie 已提交
705 706
			if r.Method == "POST" || r.Method == "DELETE" || r.Method == "PUT" ||
				(r.Method == "POST" && (r.Form.Get("_method") == "delete" || r.Form.Get("_method") == "put")) {
707
				execController.CheckXsrfCookie()
A
astaxie 已提交
708 709 710
			}
		}

A
astaxie 已提交
711
		//call prepare function
712
		execController.Prepare()
A
astaxie 已提交
713

A
fix bug  
astaxie 已提交
714
		if !w.started {
715
			//exec main logic
A
astaxie 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
			switch runMethod {
			case "Get":
				execController.Get()
			case "Post":
				execController.Post()
			case "Delete":
				execController.Delete()
			case "Put":
				execController.Put()
			case "Head":
				execController.Head()
			case "Patch":
				execController.Patch()
			case "Options":
				execController.Options()
			default:
				in := make([]reflect.Value, 0)
				method := vc.MethodByName(runMethod)
				method.Call(in)
			}
A
astaxie 已提交
736

737
			//render template
A
astaxie 已提交
738
			if !w.started && !context.Input.IsWebsocket() {
A
fix bug  
astaxie 已提交
739
				if AutoRender {
740 741 742 743
					if err := execController.Render(); err != nil {
						panic(err)
					}

A
fix bug  
astaxie 已提交
744 745 746
				}
			}
		}
A
astaxie 已提交
747

748
		// finish all runrouter. release resource
749
		execController.Finish()
750

A
astaxie 已提交
751
		//execute middleware filters
752 753
		if do_filter(AfterExec) {
			goto Admin
A
astaxie 已提交
754
		}
A
fix bug  
astaxie 已提交
755 756
	}

757
Admin:
758 759
	do_filter(FinishRouter)

760 761
	//admin module record QPS
	if EnableAdmin {
A
astaxie 已提交
762 763 764
		timeend := time.Since(starttime)
		if FilterMonitorFunc(r.Method, requestPath, timeend) {
			if runrouter != nil {
765
				go toolbox.StatisticsMap.AddStatistics(r.Method, requestPath, runrouter.Name(), timeend)
A
astaxie 已提交
766
			} else {
A
astaxie 已提交
767
				go toolbox.StatisticsMap.AddStatistics(r.Method, requestPath, "", timeend)
A
astaxie 已提交
768
			}
A
astaxie 已提交
769
		}
770
	}
A
fix bug  
astaxie 已提交
771 772
}

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
// there always should be error handler that sets error code accordingly for all unhandled errors
// in order to have custom UI for error page it's necessary to override "500" error
func (p *ControllerRegistor) getErrorHandler(errorCode string) func(rw http.ResponseWriter, r *http.Request) {
	handler := middleware.SimpleServerError
	ok := true
	if errorCode != "" {
		handler, ok = middleware.ErrorMaps[errorCode]
		if !ok {
			handler, ok = middleware.ErrorMaps["500"]
		}
		if !ok || handler == nil {
			handler = middleware.SimpleServerError
		}
	}

	return handler
}

791
func (p *ControllerRegistor) getRunMethod(method, _method string, router *controllerInfo) string {
792 793 794 795 796 797 798
	method = strings.ToLower(method)
	if router.hasMethod {
		if m, ok := router.methods[method]; ok {
			return m
		} else if m, ok = router.methods["*"]; ok {
			return m
		} else {
799 800 801 802 803 804
			if method == "POST" || strings.ToLower(_method) == "put" {
				return "Put"
			}
			if method == "POST" || strings.ToLower(_method) == "delete" {
				return "Delete"
			}
805 806 807
			return strings.Title(method)
		}
	} else {
808 809 810 811 812 813
		if method == "POST" || strings.ToLower(_method) == "put" {
			return "Put"
		}
		if method == "POST" || strings.ToLower(_method) == "delete" {
			return "Delete"
		}
814 815 816 817
		return strings.Title(method)
	}
}

A
fix bug  
astaxie 已提交
818 819 820
//responseWriter is a wrapper for the http.ResponseWriter
//started set to true if response was written to then don't execute other handler
type responseWriter struct {
821 822 823
	writer          http.ResponseWriter
	started         bool
	status          int
F
Francois 已提交
824
	contentEncoding string
A
fix bug  
astaxie 已提交
825 826 827 828 829 830 831
}

// Header returns the header map that will be sent by WriteHeader.
func (w *responseWriter) Header() http.Header {
	return w.writer.Header()
}

F
Francois 已提交
832 833 834 835 836 837 838 839 840 841
func (w *responseWriter) InitHeadContent(contentlength int64) {
	if w.contentEncoding == "gzip" {
		w.Header().Set("Content-Encoding", "gzip")
	} else if w.contentEncoding == "deflate" {
		w.Header().Set("Content-Encoding", "deflate")
	} else {
		w.Header().Set("Content-Length", strconv.FormatInt(contentlength, 10))
	}
}

A
fix bug  
astaxie 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855
// Write writes the data to the connection as part of an HTTP reply,
// and sets `started` to true
func (w *responseWriter) Write(p []byte) (int, error) {
	w.started = true
	return w.writer.Write(p)
}

// WriteHeader sends an HTTP response header with status code,
// and sets `started` to true
func (w *responseWriter) WriteHeader(code int) {
	w.status = code
	w.started = true
	w.writer.WriteHeader(code)
}