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

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

	beecontext "github.com/astaxie/beego/context"
	"github.com/astaxie/beego/middleware"
	"github.com/astaxie/beego/toolbox"
22
	"github.com/astaxie/beego/utils"
A
fix bug  
astaxie 已提交
23 24
)

25
const (
26
	// default filter execution points
27 28 29 30 31 32 33
	BeforeRouter = iota
	AfterStatic
	BeforeExec
	AfterExec
	FinishRouter
)

34
var (
35
	// supported http methods.
36
	HTTPMETHOD = []string{"get", "post", "put", "delete", "patch", "options", "head"}
A
astaxie 已提交
37 38 39 40 41 42 43 44
	// these beego.Controller's methods shouldn't reflect to AutoRouter
	exceptMethod = []string{"Init", "Prepare", "Finish", "Render", "RenderString",
		"RenderBytes", "Redirect", "Abort", "StopRun", "UrlFor", "ServeJson", "ServeJsonp",
		"ServeXml", "Input", "ParseForm", "GetString", "GetStrings", "GetInt", "GetBool",
		"GetFloat", "GetFile", "SaveToFile", "StartSession", "SetSession", "GetSession",
		"DelSession", "SessionRegenerateID", "DestroySession", "IsAjax", "GetSecureCookie",
		"SetSecureCookie", "XsrfToken", "CheckXsrfCookie", "XsrfFormHtml",
		"GetControllerAndAction"}
45
)
A
astaxie 已提交
46

U
unphp 已提交
47 48 49 50 51
// To append a slice's value into "exceptMethod", for controller's methods shouldn't reflect to AutoRouter
func ExceptMethodAppend(action string) {
	exceptMethod = append(exceptMethod, action)
}

A
fix bug  
astaxie 已提交
52 53 54 55 56
type controllerInfo struct {
	pattern        string
	regex          *regexp.Regexp
	params         map[int]string
	controllerType reflect.Type
A
astaxie 已提交
57
	methods        map[string]string
A
astaxie 已提交
58
	hasMethod      bool
A
fix bug  
astaxie 已提交
59 60
}

61
// ControllerRegistor containers registered router rules, controller handlers and filters.
A
fix bug  
astaxie 已提交
62
type ControllerRegistor struct {
A
astaxie 已提交
63 64 65 66 67 68
	routers      []*controllerInfo // regexp router storage
	fixrouters   []*controllerInfo // fixed router storage
	enableFilter bool
	filters      map[int][]*FilterRouter
	enableAuto   bool
	autoRouter   map[string]map[string]reflect.Type //key:controller key:method value:reflect.type
A
fix bug  
astaxie 已提交
69 70
}

71
// NewControllerRegistor returns a new ControllerRegistor.
A
fix bug  
astaxie 已提交
72
func NewControllerRegistor() *ControllerRegistor {
A
astaxie 已提交
73
	return &ControllerRegistor{
A
astaxie 已提交
74 75 76
		routers:    make([]*controllerInfo, 0),
		autoRouter: make(map[string]map[string]reflect.Type),
		filters:    make(map[int][]*FilterRouter),
A
astaxie 已提交
77
	}
A
fix bug  
astaxie 已提交
78 79
}

80 81 82 83 84 85 86 87 88 89
// Add controller handler and pattern rules to ControllerRegistor.
// 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")
//	Add("/api",&RestController{},"get,post:ApiFunc")
//	Add("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")
A
astaxie 已提交
90
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
A
fix bug  
astaxie 已提交
91 92 93 94 95 96
	parts := strings.Split(pattern, "/")

	j := 0
	params := make(map[int]string)
	for i, part := range parts {
		if strings.HasPrefix(part, ":") {
97
			expr := "(.*)"
A
fix bug  
astaxie 已提交
98
			//a user may choose to override the defult expression
99
			// similar to expressjs: ‘/user/:id([0-9]+)’
A
fix bug  
astaxie 已提交
100 101 102
			if index := strings.Index(part, "("); index != -1 {
				expr = part[index:]
				part = part[:index]
A
astaxie 已提交
103
				//match /user/:id:int ([0-9]+)
A
astaxie 已提交
104
				//match /post/:username:string	([\w]+)
A
astaxie 已提交
105 106
			} else if lindex := strings.LastIndex(part, ":"); lindex != 0 {
				switch part[lindex:] {
A
astaxie 已提交
107
				case ":int":
A
astaxie 已提交
108
					expr = "([0-9]+)"
A
astaxie 已提交
109
					part = part[:lindex]
A
astaxie 已提交
110
				case ":string":
A
astaxie 已提交
111
					expr = `([\w]+)`
A
astaxie 已提交
112
					part = part[:lindex]
A
astaxie 已提交
113
				}
A
fix bug  
astaxie 已提交
114 115 116 117 118
			}
			params[j] = part
			parts[i] = expr
			j++
		}
A
astaxie 已提交
119
		if strings.HasPrefix(part, "*") {
120
			expr := "(.*)"
A
astaxie 已提交
121 122
			if part == "*.*" {
				params[j] = ":path"
A
astaxie 已提交
123
				parts[i] = "([^.]+).([^.]+)"
A
astaxie 已提交
124 125 126 127 128 129 130 131 132
				j++
				params[j] = ":ext"
				j++
			} else {
				params[j] = ":splat"
				parts[i] = expr
				j++
			}
		}
A
astaxie 已提交
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
		//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 已提交
174
	}
A
astaxie 已提交
175 176
	reflectVal := reflect.ValueOf(c)
	t := reflect.Indirect(reflectVal).Type()
A
astaxie 已提交
177 178 179 180 181 182
	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 已提交
183
				panic("method mapping format is invalid")
A
astaxie 已提交
184 185 186
			}
			comma := strings.Split(colon[0], ",")
			for _, m := range comma {
187
				if m == "*" || utils.InSlice(strings.ToLower(m), HTTPMETHOD) {
A
astaxie 已提交
188
					if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
A
astaxie 已提交
189 190
						methods[strings.ToLower(m)] = colon[1]
					} else {
V
vadimi 已提交
191
						panic(colon[1] + " method doesn't exist in the controller " + t.Name())
A
astaxie 已提交
192 193
					}
				} else {
V
vadimi 已提交
194
					panic(v + " is an invalid method mapping. Method doesn't exist " + m)
A
astaxie 已提交
195 196 197 198
				}
			}
		}
	}
A
fix bug  
astaxie 已提交
199 200 201 202 203
	if j == 0 {
		//now create the Route
		route := &controllerInfo{}
		route.pattern = pattern
		route.controllerType = t
A
astaxie 已提交
204
		route.methods = methods
A
astaxie 已提交
205 206 207
		if len(methods) > 0 {
			route.hasMethod = true
		}
A
fix bug  
astaxie 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220
		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 已提交
221

A
fix bug  
astaxie 已提交
222 223 224 225
		route := &controllerInfo{}
		route.regex = regex
		route.params = params
		route.pattern = pattern
A
astaxie 已提交
226
		route.methods = methods
A
astaxie 已提交
227 228 229
		if len(methods) > 0 {
			route.hasMethod = true
		}
A
fix bug  
astaxie 已提交
230 231 232 233 234
		route.controllerType = t
		p.routers = append(p.routers, route)
	}
}

235 236 237
// Add auto router to ControllerRegistor.
// example beego.AddAuto(&MainContorlller{}),
// MainController has method List and Page.
A
astaxie 已提交
238 239
// visit the url /main/list to execute List function
// /main/page to execute Page function.
A
astaxie 已提交
240
func (p *ControllerRegistor) AddAuto(c ControllerInterface) {
A
astaxie 已提交
241
	p.enableAuto = true
A
astaxie 已提交
242 243 244 245 246 247 248 249 250 251
	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++ {
A
astaxie 已提交
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
		if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
			p.autoRouter[firstParam][rt.Method(i).Name] = ct
		}
	}
}

// Add auto router to ControllerRegistor with prefix.
// 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.
func (p *ControllerRegistor) AddAutoPrefix(prefix string, c ControllerInterface) {
	p.enableAuto = true
	reflectVal := reflect.ValueOf(c)
	rt := reflectVal.Type()
	ct := reflect.Indirect(reflectVal).Type()
	firstParam := strings.Trim(prefix, "/") + "/" + 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++ {
		if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
			p.autoRouter[firstParam][rt.Method(i).Name] = ct
		}
A
astaxie 已提交
278 279 280
	}
}

281 282
// [Deprecated] use InsertFilter.
// Add FilterFunc with pattern for action.
283 284 285 286 287
func (p *ControllerRegistor) AddFilter(pattern, action string, filter FilterFunc) error {
	mr, err := buildFilter(pattern, filter)
	if err != nil {
		return err
	}
288
	switch action {
A
astaxie 已提交
289
	case "BeforeRouter":
290 291 292 293 294 295 296 297 298 299 300
		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
301
	return nil
302 303
}

304
// Add a FilterFunc with pattern rule and action constant.
305 306 307 308 309
func (p *ControllerRegistor) InsertFilter(pattern string, pos int, filter FilterFunc) error {
	mr, err := buildFilter(pattern, filter)
	if err != nil {
		return err
	}
K
knightmare 已提交
310
	p.filters[pos] = append(p.filters[pos], mr)
311
	p.enableFilter = true
312
	return nil
A
astaxie 已提交
313 314
}

315 316
// UrlFor does another controller handler in this request function.
// it can access any controller method.
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
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
343
			if utils.InSlice(strings.ToLower(methodName), HTTPMETHOD) {
A
astaxie 已提交
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
			}
			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
374
			if utils.InSlice(strings.ToLower(methodName), HTTPMETHOD) {
A
astaxie 已提交
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
				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 ""
}

432
// Implement http.Handler interface.
A
fix bug  
astaxie 已提交
433 434 435
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	defer func() {
		if err := recover(); err != nil {
A
astaxie 已提交
436
			if err == USERSTOPRUN {
A
astaxie 已提交
437 438
				return
			}
439 440
			if _, ok := err.(middleware.HTTPException); ok {
				// catch intented errors, only for HTTP 4XX and 5XX
A
fix bug  
astaxie 已提交
441
			} else {
A
astaxie 已提交
442
				if RunMode == "dev" {
443 444 445
					if !RecoverPanic {
						panic(err)
					} else {
446 447 448 449 450 451
						if ErrorsShow {
							if handler, ok := middleware.ErrorMaps[fmt.Sprint(err)]; ok {
								handler(rw, r)
								return
							}
						}
452
						var stack string
A
astaxie 已提交
453
						Critical("the request url is ", r.URL.Path)
454 455 456 457 458 459 460
						Critical("Handler crashed with error", err)
						for i := 1; ; i++ {
							_, file, line, ok := runtime.Caller(i)
							if !ok {
								break
							}
							Critical(file, line)
A
astaxie 已提交
461
							stack = stack + fmt.Sprintln(file, line)
A
fix #16  
astaxie 已提交
462
						}
A
astaxie 已提交
463 464 465
						middleware.ShowErr(err, rw, r, stack)
					}
				} else {
466 467
					if !RecoverPanic {
						panic(err)
A
astaxie 已提交
468
					} else {
469 470 471 472
						// in production model show all infomation
						if ErrorsShow {
							handler := p.getErrorHandler(fmt.Sprint(err))
							handler(rw, r)
473
							return
A
astaxie 已提交
474
						} else {
A
astaxie 已提交
475
							Critical("the request url is ", r.URL.Path)
A
astaxie 已提交
476 477 478 479 480 481 482 483
							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 已提交
484
						}
A
fix bug  
astaxie 已提交
485
					}
A
astaxie 已提交
486
				}
A
astaxie 已提交
487

A
fix bug  
astaxie 已提交
488 489 490
			}
		}
	}()
A
astaxie 已提交
491

492 493
	starttime := time.Now()
	requestPath := r.URL.Path
494
	var runrouter reflect.Type
495
	var findrouter bool
496
	var runMethod string
497 498
	params := make(map[string]string)

A
fix bug  
astaxie 已提交
499
	w := &responseWriter{writer: rw}
A
astaxie 已提交
500
	w.Header().Set("Server", BeegoServerName)
A
astaxie 已提交
501 502

	// init context
A
astaxie 已提交
503 504 505 506 507
	context := &beecontext.Context{
		ResponseWriter: w,
		Request:        r,
		Input:          beecontext.NewInput(r),
		Output:         beecontext.NewOutput(),
A
astaxie 已提交
508
	}
A
astaxie 已提交
509 510
	context.Output.Context = context
	context.Output.EnableGzip = EnableGzip
A
astaxie 已提交
511 512 513 514 515 516

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

	// defined filter function
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	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
						}
					}
				}
			}
		}

532
		return false
533 534
	}

A
astaxie 已提交
535 536 537
	// session init
	if SessionOn {
		context.Input.CruSession = GlobalSessions.SessionStart(w, r)
538 539 540
		defer func() {
			context.Input.CruSession.SessionRelease(w)
		}()
A
astaxie 已提交
541 542
	}

543
	if !utils.InSlice(strings.ToLower(r.Method), HTTPMETHOD) {
A
astaxie 已提交
544
		http.Error(w, "Method Not Allowed", 405)
545
		goto Admin
A
astaxie 已提交
546 547
	}

548 549
	if do_filter(BeforeRouter) {
		goto Admin
A
astaxie 已提交
550 551
	}

A
fix bug  
astaxie 已提交
552 553
	//static file server
	for prefix, staticDir := range StaticDir {
A
asta.xie 已提交
554 555 556
		if len(prefix) == 0 {
			continue
		}
557
		if r.URL.Path == "/favicon.ico" {
558
			file := path.Join(staticDir, r.URL.Path)
559 560 561 562 563
			if utils.FileExists(file) {
				http.ServeFile(w, r, file)
				w.started = true
				goto Admin
			}
564
		}
A
fix bug  
astaxie 已提交
565
		if strings.HasPrefix(r.URL.Path, prefix) {
A
asta.xie 已提交
566
			if len(r.URL.Path) > len(prefix) && r.URL.Path[len(prefix)] != '/' {
567 568
				continue
			}
A
asta.xie 已提交
569 570 571 572
			if r.URL.Path == prefix && prefix[len(prefix)-1] != '/' {
				http.Redirect(rw, r, r.URL.Path+"/", 302)
				goto Admin
			}
573
			file := path.Join(staticDir, r.URL.Path[len(prefix):])
A
fix #81  
astaxie 已提交
574 575
			finfo, err := os.Stat(file)
			if err != nil {
576 577 578
				if RunMode == "dev" {
					Warn(err)
				}
A
astaxie 已提交
579
				http.NotFound(w, r)
580
				goto Admin
A
fix #81  
astaxie 已提交
581 582 583
			}
			//if the request is dir and DirectoryIndex is false then
			if finfo.IsDir() && !DirectoryIndex {
A
astaxie 已提交
584
				middleware.Exception("403", rw, r, "403 Forbidden")
585
				goto Admin
A
fix #81  
astaxie 已提交
586
			}
587

F
Francois 已提交
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
			//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)
			}
615

A
fix bug  
astaxie 已提交
616
			w.started = true
617
			goto Admin
A
fix bug  
astaxie 已提交
618 619 620
		}
	}

621 622
	if do_filter(AfterStatic) {
		goto Admin
A
astaxie 已提交
623
	}
A
fix bug  
astaxie 已提交
624

A
astaxie 已提交
625
	if CopyRequestBody {
A
astaxie 已提交
626
		context.Input.Body()
A
astaxie 已提交
627 628
	}

A
fix bug  
astaxie 已提交
629 630 631
	//first find path from the fixrouters to Improve Performance
	for _, route := range p.fixrouters {
		n := len(requestPath)
A
astaxie 已提交
632
		if requestPath == route.pattern {
A
astaxie 已提交
633
			runMethod = p.getRunMethod(r.Method, context, route)
634 635 636 637 638
			if runMethod != "" {
				runrouter = route.controllerType
				findrouter = true
				break
			}
639
		}
640
		// pattern /admin   url /admin 200  /admin/ 200
A
astaxie 已提交
641
		// pattern /admin/  url /admin 301  /admin/ 200
642
		if requestPath[n-1] != '/' && requestPath+"/" == route.pattern {
A
astaxie 已提交
643
			http.Redirect(w, r, requestPath+"/", 301)
644
			goto Admin
A
fix bug  
astaxie 已提交
645
		}
646
		if requestPath[n-1] == '/' && route.pattern+"/" == requestPath {
647 648 649 650 651 652 653
			runMethod = p.getRunMethod(r.Method, context, route)
			if runMethod != "" {
				runrouter = route.controllerType
				findrouter = true
				break
			}
		}
A
fix bug  
astaxie 已提交
654 655
	}

A
astaxie 已提交
656
	//find regex's router
A
fix bug  
astaxie 已提交
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
	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 已提交
682
				r.URL.RawQuery = url.Values(values).Encode()
A
fix bug  
astaxie 已提交
683
			}
A
astaxie 已提交
684
			runMethod = p.getRunMethod(r.Method, context, route)
685 686 687 688 689 690
			if runMethod != "" {
				runrouter = route.controllerType
				context.Input.Params = params
				findrouter = true
				break
			}
A
fix bug  
astaxie 已提交
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
	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 已提交
730 731 732 733 734 735 736 737
						//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
							}
						}
738 739 740 741 742 743 744 745 746 747 748 749
						break
					}
				}
			}
		}
	}

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

751
	if findrouter {
A
astaxie 已提交
752 753 754
		if r.Method == "POST" {
			r.ParseMultipartForm(MaxMemory)
		}
A
fix bug  
astaxie 已提交
755
		//execute middleware filters
756 757
		if do_filter(BeforeExec) {
			goto Admin
A
fix bug  
astaxie 已提交
758
		}
759

A
fix bug  
astaxie 已提交
760
		//Invoke the request handler
761
		vc := reflect.New(runrouter)
762 763 764 765
		execController, ok := vc.Interface().(ControllerInterface)
		if !ok {
			panic("controller is not ControllerInterface")
		}
A
fix bug  
astaxie 已提交
766 767

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

A
astaxie 已提交
770 771
		//if XSRF is Enable then check cookie where there has any cookie in the  request's cookie _csrf
		if EnableXSRF {
772
			execController.XsrfToken()
A
astaxie 已提交
773 774
			if r.Method == "POST" || r.Method == "DELETE" || r.Method == "PUT" ||
				(r.Method == "POST" && (r.Form.Get("_method") == "delete" || r.Form.Get("_method") == "put")) {
775
				execController.CheckXsrfCookie()
A
astaxie 已提交
776 777 778
			}
		}

A
astaxie 已提交
779
		//call prepare function
780
		execController.Prepare()
A
astaxie 已提交
781

A
fix bug  
astaxie 已提交
782
		if !w.started {
783
			//exec main logic
A
astaxie 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
			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 已提交
804

805
			//render template
A
astaxie 已提交
806
			if !w.started && !context.Input.IsWebsocket() {
A
fix bug  
astaxie 已提交
807
				if AutoRender {
808 809 810 811
					if err := execController.Render(); err != nil {
						panic(err)
					}

A
fix bug  
astaxie 已提交
812 813 814
				}
			}
		}
A
astaxie 已提交
815

816
		// finish all runrouter. release resource
817
		execController.Finish()
818

A
astaxie 已提交
819
		//execute middleware filters
820 821
		if do_filter(AfterExec) {
			goto Admin
A
astaxie 已提交
822
		}
A
fix bug  
astaxie 已提交
823 824
	}

825
Admin:
826 827
	do_filter(FinishRouter)

828 829
	//admin module record QPS
	if EnableAdmin {
A
astaxie 已提交
830 831 832
		timeend := time.Since(starttime)
		if FilterMonitorFunc(r.Method, requestPath, timeend) {
			if runrouter != nil {
833
				go toolbox.StatisticsMap.AddStatistics(r.Method, requestPath, runrouter.Name(), timeend)
A
astaxie 已提交
834
			} else {
A
astaxie 已提交
835
				go toolbox.StatisticsMap.AddStatistics(r.Method, requestPath, "", timeend)
A
astaxie 已提交
836
			}
A
astaxie 已提交
837
		}
838
	}
A
fix bug  
astaxie 已提交
839 840
}

841 842
// 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.
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
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
}

859 860 861
// returns method name from request header or form field.
// sometimes browsers can't create PUT and DELETE request.
// set a form field "_method" instead.
A
astaxie 已提交
862
func (p *ControllerRegistor) getRunMethod(method string, context *beecontext.Context, router *controllerInfo) string {
863
	method = strings.ToLower(method)
864 865 866 867 868 869
	if method == "post" && strings.ToLower(context.Input.Query("_method")) == "put" {
		method = "put"
	}
	if method == "post" && strings.ToLower(context.Input.Query("_method")) == "delete" {
		method = "delete"
	}
870 871 872 873 874
	if router.hasMethod {
		if m, ok := router.methods[method]; ok {
			return m
		} else if m, ok = router.methods["*"]; ok {
			return m
875
		} else {
876
			return ""
877 878 879 880 881 882
		}
	} else {
		return strings.Title(method)
	}
}

A
fix bug  
astaxie 已提交
883 884 885
//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 {
886 887 888
	writer          http.ResponseWriter
	started         bool
	status          int
F
Francois 已提交
889
	contentEncoding string
A
fix bug  
astaxie 已提交
890 891 892 893 894 895 896
}

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

897
// Init content-length header.
F
Francois 已提交
898 899 900 901 902 903 904 905 906 907
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 已提交
908
// Write writes the data to the connection as part of an HTTP reply,
909 910
// and sets `started` to true.
// started means the response has sent out.
A
fix bug  
astaxie 已提交
911 912 913 914 915 916
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,
917
// and sets `started` to true.
A
fix bug  
astaxie 已提交
918 919 920 921 922
func (w *responseWriter) WriteHeader(code int) {
	w.status = code
	w.started = true
	w.writer.WriteHeader(code)
}
A
astaxie 已提交
923 924 925 926 927 928 929 930 931 932

// hijacker for http
func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	hj, ok := w.writer.(http.Hijacker)
	if !ok {
		println("supported?")
		return nil, nil, errors.New("webserver doesn't support hijacking")
	}
	return hj.Hijack()
}