router.go 23.7 KB
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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 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 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 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 616 617 618 619 620 621 622 623 624 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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
package beego

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"time"

	beecontext "github.com/astaxie/beego/context"
	"github.com/astaxie/beego/middleware"
	"github.com/astaxie/beego/toolbox"
)

const (
	BeforeRouter = iota
	AfterStatic
	BeforeExec
	AfterExec
	FinishRouter
)

var HTTPMETHOD = []string{"get", "post", "put", "delete", "patch", "options", "head"}

type controllerInfo struct {
	pattern        string
	regex          *regexp.Regexp
	params         map[int]string
	controllerType reflect.Type
	methods        map[string]string
	hasMethod      bool
}

type ControllerRegistor struct {
	routers      []*controllerInfo
	fixrouters   []*controllerInfo
	enableFilter bool
	filters      map[int][]*FilterRouter
	enableAuto   bool
	autoRouter   map[string]map[string]reflect.Type //key:controller key:method value:reflect.type
}

func NewControllerRegistor() *ControllerRegistor {
	return &ControllerRegistor{
		routers:    make([]*controllerInfo, 0),
		autoRouter: make(map[string]map[string]reflect.Type),
		filters:    make(map[int][]*FilterRouter),
	}
}

//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) {
	parts := strings.Split(pattern, "/")

	j := 0
	params := make(map[int]string)
	for i, part := range parts {
		if strings.HasPrefix(part, ":") {
			expr := "(.+)"
			//a user may choose to override the defult expression
			// similar to expressjs: ‘/user/:id([0-9]+)’
			if index := strings.Index(part, "("); index != -1 {
				expr = part[index:]
				part = part[:index]
				//match /user/:id:int ([0-9]+)
				//match /post/:username:string	([\w]+)
			} else if lindex := strings.LastIndex(part, ":"); lindex != 0 {
				switch part[lindex:] {
				case ":int":
					expr = "([0-9]+)"
					part = part[:lindex]
				case ":string":
					expr = `([\w]+)`
					part = part[:lindex]
				}
			}
			params[j] = part
			parts[i] = expr
			j++
		}
		if strings.HasPrefix(part, "*") {
			expr := "(.+)"
			if part == "*.*" {
				params[j] = ":path"
				parts[i] = "([^.]+).([^.]+)"
				j++
				params[j] = ":ext"
				j++
			} else {
				params[j] = ":splat"
				parts[i] = expr
				j++
			}
		}
		//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)
		}
	}
	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 {
				if m == "*" || inSlice(strings.ToLower(m), HTTPMETHOD) {
					if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
						methods[strings.ToLower(m)] = colon[1]
					} else {
						panic(colon[1] + " method doesn't exist in the controller " + t.Name())
					}
				} else {
					panic(v + " is an invalid method mapping. Method doesn't exist " + m)
				}
			}
		}
	}
	if j == 0 {
		//now create the Route
		route := &controllerInfo{}
		route.pattern = pattern
		route.controllerType = t
		route.methods = methods
		if len(methods) > 0 {
			route.hasMethod = true
		}
		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

		route := &controllerInfo{}
		route.regex = regex
		route.params = params
		route.pattern = pattern
		route.methods = methods
		if len(methods) > 0 {
			route.hasMethod = true
		}
		route.controllerType = t
		p.routers = append(p.routers, route)
	}
}

func (p *ControllerRegistor) AddAuto(c ControllerInterface) {
	p.enableAuto = true
	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
	}
}

func (p *ControllerRegistor) AddFilter(pattern, action string, filter FilterFunc) {
	mr := buildFilter(pattern, filter)
	switch action {
	case "BeforeRouter":
		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
}

func (p *ControllerRegistor) InsertFilter(pattern string, pos int, filter FilterFunc) {
	mr := buildFilter(pattern, filter)
	p.filters[pos] = append(p.filters[pos], mr)
	p.enableFilter = true
}

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
			if inSlice(strings.ToLower(methodName), HTTPMETHOD) {
				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
			if inSlice(strings.ToLower(methodName), HTTPMETHOD) {
				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 ""
}

// AutoRoute
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
			if _, ok := err.(middleware.HTTPException); ok {
				// catch intented errors, only for HTTP 4XX and 5XX
			} else {
				if ErrorsShow {
					handler := p.getErrorHandler(fmt.Sprint(err))
					handler(rw, r)
				} else {
					if !RecoverPanic {
						// go back to panic
						panic(err)
					} else {
						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)
							if RunMode == "dev" {
								stack = stack + fmt.Sprintln(file, line)
							}
						}
						if RunMode == "dev" {
							middleware.ShowErr(err, rw, r, stack)
						}
					}
				}
			}
		}
	}()

	starttime := time.Now()
	requestPath := r.URL.Path
	var runrouter *controllerInfo
	var findrouter bool
	params := make(map[string]string)

	w := &responseWriter{writer: rw}
	w.Header().Set("Server", BeegoServerName)
	context := &beecontext.Context{
		ResponseWriter: w,
		Request:        r,
		Input:          beecontext.NewInput(r),
		Output:         beecontext.NewOutput(w),
	}
	context.Output.Context = context
	context.Output.EnableGzip = EnableGzip

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

	if !inSlice(strings.ToLower(r.Method), HTTPMETHOD) {
		http.Error(w, "Method Not Allowed", 405)
		goto Admin
	}

	if p.enableFilter {
		if l, ok := p.filters[BeforeRouter]; ok {
			for _, filterR := range l {
				if ok, p := filterR.ValidRouter(r.URL.Path); ok {
					context.Input.Params = p
					filterR.filterFunc(context)
					if w.started {
						goto Admin
					}
				}
			}
		}
	}

	//static file server
	for prefix, staticDir := range StaticDir {
		if r.URL.Path == "/favicon.ico" {
			file := staticDir + r.URL.Path
			http.ServeFile(w, r, file)
			w.started = true
			goto Admin
		}
		if strings.HasPrefix(r.URL.Path, prefix) {
			file := staticDir + r.URL.Path[len(prefix):]
			finfo, err := os.Stat(file)
			if err != nil {
				if RunMode == "dev" {
					Warn(err)
				}
				http.NotFound(w, r)
				goto Admin
			}
			//if the request is dir and DirectoryIndex is false then
			if finfo.IsDir() && !DirectoryIndex {
				middleware.Exception("403", rw, r, "403 Forbidden")
				goto Admin
			}
			http.ServeFile(w, r, file)
			w.started = true
			goto Admin
		}
	}

	// session init after static file
	if SessionOn {
		context.Input.CruSession = GlobalSessions.SessionStart(w, r)
	}

	if p.enableFilter {
		if l, ok := p.filters[AfterStatic]; ok {
			for _, filterR := range l {
				if ok, p := filterR.ValidRouter(r.URL.Path); ok {
					context.Input.Params = p
					filterR.filterFunc(context)
					if w.started {
						goto Admin
					}
				}
			}
		}
	}

	if CopyRequestBody {
		context.Input.Body()
	}

	//first find path from the fixrouters to Improve Performance
	for _, route := range p.fixrouters {
		n := len(requestPath)
		if requestPath == route.pattern {
			runrouter = route
			findrouter = true
			break
		}
		// pattern /admin   url /admin 200  /admin/ 404
		// pattern /admin/  url /admin 301  /admin/ 200
		if requestPath[n-1] != '/' && len(route.pattern) == n+1 &&
			route.pattern[n] == '/' && route.pattern[:n] == requestPath {
			http.Redirect(w, r, requestPath+"/", 301)
			goto Admin
		}
	}

	//find regex's router
	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
				r.URL.RawQuery = url.Values(values).Encode()
			}
			runrouter = route
			findrouter = true
			break
		}
	}

	context.Input.Params = params

	if runrouter != nil {
		if r.Method == "POST" {
			r.ParseMultipartForm(MaxMemory)
		}
		//execute middleware filters
		if p.enableFilter {
			if l, ok := p.filters[BeforeExec]; ok {
				for _, filterR := range l {
					if ok, p := filterR.ValidRouter(r.URL.Path); ok {
						context.Input.Params = p
						filterR.filterFunc(context)
						if w.started {
							goto Admin
						}
					}
				}
			}
		}
		//Invoke the request handler
		vc := reflect.New(runrouter.controllerType)

		//call the controller init function
		method := vc.MethodByName("Init")
		in := make([]reflect.Value, 3)
		in[0] = reflect.ValueOf(context)
		in[1] = reflect.ValueOf(runrouter.controllerType.Name())
		in[2] = reflect.ValueOf(vc.Interface())
		method.Call(in)

		//if XSRF is Enable then check cookie where there has any cookie in the  request's cookie _csrf
		if EnableXSRF {
			in = make([]reflect.Value, 0)
			method = vc.MethodByName("XsrfToken")
			method.Call(in)
			if r.Method == "POST" || r.Method == "DELETE" || r.Method == "PUT" ||
				(r.Method == "POST" && (r.Form.Get("_method") == "delete" || r.Form.Get("_method") == "put")) {
				method = vc.MethodByName("CheckXsrfCookie")
				method.Call(in)
			}
		}

		//call prepare function
		in = make([]reflect.Value, 0)
		method = vc.MethodByName("Prepare")
		method.Call(in)

		//if response has written,yes don't run next
		if !w.started {
			if r.Method == "GET" {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["get"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Get")
					}
				} else {
					method = vc.MethodByName("Get")
				}
				method.Call(in)
			} else if r.Method == "HEAD" {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["head"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Head")
					}
				} else {
					method = vc.MethodByName("Head")
				}

				method.Call(in)
			} else if r.Method == "DELETE" || (r.Method == "POST" && r.Form.Get("_method") == "delete") {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["delete"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Delete")
					}
				} else {
					method = vc.MethodByName("Delete")
				}
				method.Call(in)
			} else if r.Method == "PUT" || (r.Method == "POST" && r.Form.Get("_method") == "put") {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["put"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Put")
					}
				} else {
					method = vc.MethodByName("Put")
				}
				method.Call(in)
			} else if r.Method == "POST" {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["post"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Post")
					}
				} else {
					method = vc.MethodByName("Post")
				}
				method.Call(in)
			} else if r.Method == "PATCH" {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["patch"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Patch")
					}
				} else {
					method = vc.MethodByName("Patch")
				}
				method.Call(in)
			} else if r.Method == "OPTIONS" {
				if runrouter.hasMethod {
					if m, ok := runrouter.methods["options"]; ok {
						method = vc.MethodByName(m)
					} else if m, ok = runrouter.methods["*"]; ok {
						method = vc.MethodByName(m)
					} else {
						method = vc.MethodByName("Options")
					}
				} else {
					method = vc.MethodByName("Options")
				}
				method.Call(in)
			}
			gotofunc := vc.Elem().FieldByName("gotofunc").String()
			if gotofunc != "" {
				method = vc.MethodByName(gotofunc)
				if method.IsValid() {
					method.Call(in)
				} else {
					panic("gotofunc is exists:" + gotofunc)
				}
			}
			if !w.started && !context.Input.IsWebsocket() {
				if AutoRender {
					method = vc.MethodByName("Render")
					method.Call(in)
				}
			}
		}

		method = vc.MethodByName("Finish")
		method.Call(in)
		//execute middleware filters
		if p.enableFilter {
			if l, ok := p.filters[AfterExec]; ok {
				for _, filterR := range l {
					if ok, p := filterR.ValidRouter(r.URL.Path); ok {
						context.Input.Params = p
						filterR.filterFunc(context)
						if w.started {
							goto Admin
						}
					}
				}
			}
		}
		method = vc.MethodByName("Destructor")
		method.Call(in)
	}

	//start autorouter

	if p.enableAuto {
		if !findrouter {
			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 strings.ToLower(requestPath) == "/"+cName {
					http.Redirect(w, r, requestPath+"/", 301)
					goto Admin
				}

				if strings.ToLower(requestPath) == "/"+cName+"/" {
					requestPath = requestPath + "index"
				}
				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] == "/") {
							if r.Method == "POST" {
								r.ParseMultipartForm(MaxMemory)
							}
							// set find
							findrouter = true
							//execute middleware filters
							if p.enableFilter {
								if l, ok := p.filters[BeforeExec]; ok {
									for _, filterR := range l {
										if ok, p := filterR.ValidRouter(r.URL.Path); ok {
											context.Input.Params = p
											filterR.filterFunc(context)
											if w.started {
												goto Admin
											}
										}
									}
								}
							}
							//parse params
							otherurl := requestPath[len("/"+cName+"/"+strings.ToLower(mName)):]
							if len(otherurl) > 1 {
								plist := strings.Split(otherurl, "/")
								for k, v := range plist[1:] {
									params[strconv.Itoa(k)] = v
								}
							}
							//Invoke the request handler
							vc := reflect.New(controllerType)

							//call the controller init function
							init := vc.MethodByName("Init")
							in := make([]reflect.Value, 3)
							in[0] = reflect.ValueOf(context)
							in[1] = reflect.ValueOf(controllerType.Name())
							in[2] = reflect.ValueOf(vc.Interface())
							init.Call(in)
							//call prepare function
							in = make([]reflect.Value, 0)
							method := vc.MethodByName("Prepare")
							method.Call(in)
							method = vc.MethodByName(mName)
							method.Call(in)
							//if XSRF is Enable then check cookie where there has any cookie in the  request's cookie _csrf
							if EnableXSRF {
								method = vc.MethodByName("XsrfToken")
								method.Call(in)
								if r.Method == "POST" || r.Method == "DELETE" || r.Method == "PUT" ||
									(r.Method == "POST" && (r.Form.Get("_method") == "delete" || r.Form.Get("_method") == "put")) {
									method = vc.MethodByName("CheckXsrfCookie")
									method.Call(in)
								}
							}
							if !w.started && !context.Input.IsWebsocket() {
								if AutoRender {
									method = vc.MethodByName("Render")
									method.Call(in)
								}
							}
							method = vc.MethodByName("Finish")
							method.Call(in)
							//execute middleware filters
							if p.enableFilter {
								if l, ok := p.filters[AfterExec]; ok {
									for _, filterR := range l {
										if ok, p := filterR.ValidRouter(r.URL.Path); ok {
											context.Input.Params = p
											filterR.filterFunc(context)
											if w.started {
												goto Admin
											}
										}
									}
								}
							}
							method = vc.MethodByName("Destructor")
							method.Call(in)
							goto Admin
						}
					}
				}
			}
		}
	}

	//if no matches to url, throw a not found exception
	if !findrouter {
		middleware.Exception("404", rw, r, "")
	}

Admin:
	if p.enableFilter {
		if l, ok := p.filters[FinishRouter]; ok {
			for _, filterR := range l {
				if ok, p := filterR.ValidRouter(r.URL.Path); ok {
					context.Input.Params = p
					filterR.filterFunc(context)
					if w.started {
						break
					}
				}
			}
		}
	}
	//admin module record QPS
	if EnableAdmin {
		timeend := time.Since(starttime)
		if FilterMonitorFunc(r.Method, requestPath, timeend) {
			if runrouter != nil {
				go toolbox.StatisticsMap.AddStatistics(r.Method, requestPath, runrouter.controllerType.Name(), timeend)
			} else {
				go toolbox.StatisticsMap.AddStatistics(r.Method, requestPath, "", timeend)
			}
		}
	}
}

// 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
}

//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 {
	writer  http.ResponseWriter
	started bool
	status  int
}

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

// 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)
}