func (w *responseWriter) WriteHeader(code int) {
	w.status = code
	w.started = true
	w.writer.WriteHeader(code)
}
WriteHeader sends an HTTP response header with status code,
and sets `started` to true.
package beego
import (
	"bufio"
	"errors"
	"fmt"
	"net"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"time"
	beecontext "github.com/astaxie/beego/context"
	"github.com/astaxie/beego/middleware"
	"github.com/astaxie/beego/toolbox"
	"github.com/astaxie/beego/utils"
)
const (
	BeforeStatic = iota
	BeforeRouter
	BeforeExec
	AfterExec
	FinishRouter
)
const (
	routerTypeBeego = iota
	routerTypeRESTFul
	routerTypeHandler
)
var (
	HTTPMETHOD = map[string]string{
		"GET":     "GET",
		"POST":    "POST",
		"PUT":     "PUT",
		"DELETE":  "DELETE",
		"PATCH":   "PATCH",
		"OPTIONS": "OPTIONS",
		"HEAD":    "HEAD",
		"TRACE":   "TRACE",
		"CONNECT": "CONNECT",
	}
	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"}
	url_placeholder = "{{placeholder}}"
)
func ExceptMethodAppend(action string) {
	exceptMethod = append(exceptMethod, action)
}
type controllerInfo struct {
	pattern        string
	controllerType reflect.Type
	methods        map[string]string
	handler        http.Handler
	runfunction    FilterFunc
	routerType     int
}
type ControllerRegistor struct {
	routers      map[string]*Tree
	enableFilter bool
	filters      map[int][]*FilterRouter
}
func NewControllerRegister() *ControllerRegistor {
	return &ControllerRegistor{
		routers: make(map[string]*Tree),
		filters: make(map[int][]*FilterRouter),
	}
}
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface, mappingMethods ...string) {
	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 _, ok := HTTPMETHOD[strings.ToUpper(m)]; m == "*" || ok {
					if val := reflectVal.MethodByName(colon[1]); val.IsValid() {
						methods[strings.ToUpper(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)
				}
			}
		}
	}
	route := &controllerInfo{}
	route.pattern = pattern
	route.methods = methods
	route.routerType = routerTypeBeego
	route.controllerType = t
	if len(methods) == 0 {
		for _, m := range HTTPMETHOD {
			p.addToRouter(m, pattern, route)
		}
	} else {
		for k, _ := range methods {
			if k == "*" {
				for _, m := range HTTPMETHOD {
					p.addToRouter(m, pattern, route)
				}
			} else {
				p.addToRouter(k, pattern, route)
			}
		}
	}
}
func (p *ControllerRegistor) addToRouter(method, pattern string, r *controllerInfo) {
	if t, ok := p.routers[method]; ok {
		t.AddRouter(pattern, r)
	} else {
		t := NewTree()
		t.AddRouter(pattern, r)
		p.routers[method] = t
	}
}
func (p *ControllerRegistor) Include(cList ...ControllerInterface) {
	if RunMode == "dev" {
		skip := make(map[string]bool, 10)
		for _, c := range cList {
			reflectVal := reflect.ValueOf(c)
			t := reflect.Indirect(reflectVal).Type()
			gopath := os.Getenv("GOPATH")
			if gopath == "" {
				panic("you are in dev mode. So please set gopath")
			}
			pkgpath := ""
			wgopath := filepath.SplitList(gopath)
			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
					parserPkg(pkgpath, t.PkgPath())
				}
			}
		}
	}
	for _, c := range cList {
		reflectVal := reflect.ValueOf(c)
		t := reflect.Indirect(reflectVal).Type()
		key := t.PkgPath() + ":" + t.Name()
		if comm, ok := GlobalControllerRouter[key]; ok {
			for _, a := range comm {
				p.Add(a.Router, c, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method)
			}
		}
	}
}
func (p *ControllerRegistor) Get(pattern string, f FilterFunc) {
	p.AddMethod("get", pattern, f)
}
func (p *ControllerRegistor) Post(pattern string, f FilterFunc) {
	p.AddMethod("post", pattern, f)
}
func (p *ControllerRegistor) Put(pattern string, f FilterFunc) {
	p.AddMethod("put", pattern, f)
}
func (p *ControllerRegistor) Delete(pattern string, f FilterFunc) {
	p.AddMethod("delete", pattern, f)
}
func (p *ControllerRegistor) Head(pattern string, f FilterFunc) {
	p.AddMethod("head", pattern, f)
}
func (p *ControllerRegistor) Patch(pattern string, f FilterFunc) {
	p.AddMethod("patch", pattern, f)
}
func (p *ControllerRegistor) Options(pattern string, f FilterFunc) {
	p.AddMethod("options", pattern, f)
}
func (p *ControllerRegistor) Any(pattern string, f FilterFunc) {
	p.AddMethod("*", pattern, f)
}
func (p *ControllerRegistor) AddMethod(method, pattern string, f FilterFunc) {
	if _, ok := HTTPMETHOD[strings.ToUpper(method)]; method != "*" && !ok {
		panic("not support http method: " + method)
	}
	route := &controllerInfo{}
	route.pattern = pattern
	route.routerType = routerTypeRESTFul
	route.runfunction = f
	methods := make(map[string]string)
	if method == "*" {
		for _, val := range HTTPMETHOD {
			methods[val] = val
		}
	} else {
		methods[strings.ToUpper(method)] = strings.ToUpper(method)
	}
	route.methods = methods
	for k, _ := range methods {
		if k == "*" {
			for _, m := range HTTPMETHOD {
				p.addToRouter(m, pattern, route)
			}
		} else {
			p.addToRouter(k, pattern, route)
		}
	}
}
func (p *ControllerRegistor) Handler(pattern string, h http.Handler, options ...interface{}) {
	route := &controllerInfo{}
	route.pattern = pattern
	route.routerType = routerTypeHandler
	route.handler = h
	if len(options) > 0 {
		if _, ok := options[0].(bool); ok {
			pattern = path.Join(pattern, "?:all")
		}
	}
	for _, m := range HTTPMETHOD {
		p.addToRouter(m, pattern, route)
	}
}
func (p *ControllerRegistor) AddAuto(c ControllerInterface) {
	p.AddAutoPrefix("/", c)
}
func (p *ControllerRegistor) AddAutoPrefix(prefix string, c ControllerInterface) {
	reflectVal := reflect.ValueOf(c)
	rt := reflectVal.Type()
	ct := reflect.Indirect(reflectVal).Type()
	controllerName := strings.TrimSuffix(ct.Name(), "Controller")
	for i := 0; i < rt.NumMethod(); i++ {
		if !utils.InSlice(rt.Method(i).Name, exceptMethod) {
			route := &controllerInfo{}
			route.routerType = routerTypeBeego
			route.methods = map[string]string{"*": rt.Method(i).Name}
			route.controllerType = ct
			pattern := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name), "*")
			patternInit := path.Join(prefix, controllerName, rt.Method(i).Name, "*")
			patternfix := path.Join(prefix, strings.ToLower(controllerName), strings.ToLower(rt.Method(i).Name))
			patternfixInit := path.Join(prefix, controllerName, rt.Method(i).Name)
			route.pattern = pattern
			for _, m := range HTTPMETHOD {
				p.addToRouter(m, pattern, route)
				p.addToRouter(m, patternInit, route)
				p.addToRouter(m, patternfix, route)
				p.addToRouter(m, patternfixInit, route)
			}
		}
	}
}
func (p *ControllerRegistor) InsertFilter(pattern string, pos int, filter FilterFunc) error {
	mr := new(FilterRouter)
	mr.tree = NewTree()
	mr.pattern = pattern
	mr.filterFunc = filter
	mr.tree.AddRouter(pattern, true)
	return p.insertFilterRouter(pos, mr)
}
func (p *ControllerRegistor) insertFilterRouter(pos int, mr *FilterRouter) error {
	p.filters[pos] = append(p.filters[pos], mr)
	p.enableFilter = true
	return nil
}
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 ""
	}
	params := make(map[string]string)
	if len(values) > 0 {
		key := ""
		for k, v := range values {
			if k%2 == 0 {
				key = v
			} else {
				params[key] = v
			}
		}
	}
	controllName := strings.Join(paths[:len(paths)-1], ".")
	methodName := paths[len(paths)-1]
	for _, t := range p.routers {
		ok, url := p.geturl(t, "/", controllName, methodName, params)
		if ok {
			return url
		}
	}
	return ""
}
func (p *ControllerRegistor) geturl(t *Tree, url, controllName, methodName string, params map[string]string) (bool, string) {
	for k, subtree := range t.fixrouters {
		u := path.Join(url, k)
		ok, u := p.geturl(subtree, u, controllName, methodName, params)
		if ok {
			return ok, u
		}
	}
	if t.wildcard != nil {
		url = path.Join(url, url_placeholder)
		ok, u := p.geturl(t.wildcard, url, controllName, methodName, params)
		if ok {
			return ok, u
		}
	}
	for _, l := range t.leaves {
		if c, ok := l.runObject.(*controllerInfo); ok {
			if c.routerType == routerTypeBeego && c.controllerType.Name() == controllName {
				find := false
				if _, ok := HTTPMETHOD[strings.ToUpper(methodName)]; ok {
					if len(c.methods) == 0 {
						find = true
					} else if m, ok := c.methods[strings.ToUpper(methodName)]; ok && m == strings.ToUpper(methodName) {
						find = true
					} else if m, ok = c.methods["*"]; ok && m == methodName {
						find = true
					}
				}
				if !find {
					for _, md := range c.methods {
						if md == methodName {
							find = true
						}
					}
				}
				if find {
					if l.regexps == nil {
						if len(l.wildcards) == 0 {
							return true, strings.Replace(url, "/"+url_placeholder, "", 1) + tourl(params)
						}
						if len(l.wildcards) == 1 {
							if v, ok := params[l.wildcards[0]]; ok {
								delete(params, l.wildcards[0])
								return true, strings.Replace(url, url_placeholder, v, 1) + tourl(params)
							} else {
								return false, ""
							}
						}
						if len(l.wildcards) == 3 && l.wildcards[0] == "." {
							if p, ok := params[":path"]; ok {
								if e, isok := params[":ext"]; isok {
									delete(params, ":path")
									delete(params, ":ext")
									return true, strings.Replace(url, url_placeholder, p+"."+e, -1) + tourl(params)
								}
							}
						}
						canskip := false
						for _, v := range l.wildcards {
							if v == ":" {
								canskip = true
								continue
							}
							if u, ok := params[v]; ok {
								delete(params, v)
								url = strings.Replace(url, url_placeholder, u, 1)
							} else {
								if canskip {
									canskip = false
									continue
								} else {
									return false, ""
								}
							}
						}
						return true, url + tourl(params)
					} else {
						var i int
						var startreg bool
						regurl := ""
						for _, v := range strings.Trim(l.regexps.String(), "^$") {
							if v == '(' {
								startreg = true
								continue
							} else if v == ')' {
								startreg = false
								if v, ok := params[l.wildcards[i]]; ok {
									delete(params, l.wildcards[i])
									regurl = regurl + v
									i++
								} else {
									break
								}
							} else if !startreg {
								regurl = string(append([]rune(regurl), v))
							}
						}
						if l.regexps.MatchString(regurl) {
							ps := strings.Split(regurl, "/")
							for _, p := range ps {
								url = strings.Replace(url, url_placeholder, p, 1)
							}
							return true, url + tourl(params)
						}
					}
				}
			}
		}
	}
	return false, ""
}
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	defer p.recoverPanic(rw, r)
	starttime := time.Now()
	var runrouter reflect.Type
	var findrouter bool
	var runMethod string
	var routerInfo *controllerInfo
	w := &responseWriter{writer: rw}
	if RunMode == "dev" {
		w.Header().Set("Server", BeegoServerName)
	}
	context := &beecontext.Context{
		ResponseWriter: w,
		Request:        r,
		Input:          beecontext.NewInput(r),
		Output:         beecontext.NewOutput(),
	}
	context.Output.Context = context
	context.Output.EnableGzip = EnableGzip
	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
						}
					}
				}
			}
		}
		return false
	}
	if _, ok := HTTPMETHOD[r.Method]; !ok {
		http.Error(w, "Method Not Allowed", 405)
		goto Admin
	}
	if do_filter(BeforeStatic) {
		goto Admin
	}
	serverStaticRouter(context)
	if w.started {
		findrouter = true
		goto Admin
	}
	if SessionOn {
		context.Input.CruSession = GlobalSessions.SessionStart(w, r)
		defer func() {
			context.Input.CruSession.SessionRelease(w)
		}()
	}
	if r.Method != "GET" && r.Method != "HEAD" {
		if CopyRequestBody && !context.Input.IsUpload() {
			context.Input.CopyBody()
		}
		context.Input.ParseFormOrMulitForm(MaxMemory)
	}
	if do_filter(BeforeRouter) {
		goto Admin
	}
	if context.Input.RunController != nil && context.Input.RunMethod != "" {
		findrouter = true
		runMethod = context.Input.RunMethod
		runrouter = context.Input.RunController
	}
	if !findrouter {
		if t, ok := p.routers[r.Method]; ok {
			runObject, p := t.Match(r.URL.Path)
			if r, ok := runObject.(*controllerInfo); ok {
				routerInfo = r
				findrouter = true
				if splat, ok := p[":splat"]; ok {
					splatlist := strings.Split(splat, "/")
					for k, v := range splatlist {
						p[strconv.Itoa(k)] = v
					}
				}
				context.Input.Params = p
			}
		}
	}
	if !findrouter {
		middleware.Exception("404", rw, r, "")
		goto Admin
	}
	if findrouter {
		if do_filter(BeforeExec) {
			goto Admin
		}
		isRunable := false
		if routerInfo != nil {
			if routerInfo.routerType == routerTypeRESTFul {
				if _, ok := routerInfo.methods[r.Method]; ok {
					isRunable = true
					routerInfo.runfunction(context)
				} else {
					middleware.Exception("405", rw, r, "Method Not Allowed")
					goto Admin
				}
			} else if routerInfo.routerType == routerTypeHandler {
				isRunable = true
				routerInfo.handler.ServeHTTP(rw, r)
			} else {
				runrouter = routerInfo.controllerType
				method := r.Method
				if r.Method == "POST" && context.Input.Query("_method") == "PUT" {
					method = "PUT"
				}
				if r.Method == "POST" && context.Input.Query("_method") == "DELETE" {
					method = "DELETE"
				}
				if m, ok := routerInfo.methods[method]; ok {
					runMethod = m
				} else if m, ok = routerInfo.methods["*"]; ok {
					runMethod = m
				} else {
					runMethod = method
				}
			}
		}
		if !isRunable {
			vc := reflect.New(runrouter)
			execController, ok := vc.Interface().(ControllerInterface)
			if !ok {
				panic("controller is not ControllerInterface")
			}
			execController.Init(context, runrouter.Name(), runMethod, vc.Interface())
			execController.Prepare()
			if EnableXSRF {
				execController.XsrfToken()
				if r.Method == "POST" || r.Method == "DELETE" || r.Method == "PUT" ||
					(r.Method == "POST" && (context.Input.Query("_method") == "DELETE" || context.Input.Query("_method") == "PUT")) {
					execController.CheckXsrfCookie()
				}
			}
			execController.URLMapping()
			if !w.started {
				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:
					if !execController.HandlerFunc(runMethod) {
						in := make([]reflect.Value, 0)
						method := vc.MethodByName(runMethod)
						method.Call(in)
					}
				}
				if !w.started && context.Output.Status == 0 {
					if AutoRender {
						if err := execController.Render(); err != nil {
							panic(err)
						}
					}
				}
			}
			execController.Finish()
		}
		if do_filter(AfterExec) {
			goto Admin
		}
	}
	do_filter(FinishRouter)
Admin:
	timeend := time.Since(starttime)
	if EnableAdmin {
		if FilterMonitorFunc(r.Method, r.URL.Path, timeend) {
			if runrouter != nil {
				go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, runrouter.Name(), timeend)
			} else {
				go toolbox.StatisticsMap.AddStatistics(r.Method, r.URL.Path, "", timeend)
			}
		}
	}
	if RunMode == "dev" {
		var devinfo string
		if findrouter {
			if routerInfo != nil {
				devinfo = fmt.Sprintf("| % -10s | % -40s | % -16s | % -10s | % -40s |", r.Method, r.URL.Path, timeend.String(), "match", routerInfo.pattern)
			} else {
				devinfo = fmt.Sprintf("| % -10s | % -40s | % -16s | % -10s |", r.Method, r.URL.Path, timeend.String(), "match")
			}
		} else {
			devinfo = fmt.Sprintf("| % -10s | % -40s | % -16s | % -10s |", r.Method, r.URL.Path, timeend.String(), "notmatch")
		}
		Debug(devinfo)
	}
	if context.Output.Status != 0 {
		w.writer.WriteHeader(context.Output.Status)
	}
}
func (p *ControllerRegistor) recoverPanic(rw http.ResponseWriter, r *http.Request) {
	if err := recover(); err != nil {
		if err == USERSTOPRUN {
			return
		}
		if _, ok := err.(middleware.HTTPException); ok {
		} else {
			if RunMode == "dev" {
				if !RecoverPanic {
					panic(err)
				} else {
					if ErrorsShow {
						if handler, ok := middleware.ErrorMaps[fmt.Sprint(err)]; ok {
							handler(rw, r)
							return
						}
					}
					var stack string
					Critical("the request url is ", r.URL.Path)
					Critical("Handler crashed with error", err)
					for i := 1; ; i++ {
						_, file, line, ok := runtime.Caller(i)
						if !ok {
							break
						}
						Critical(fmt.Sprintf("%s:%d", file, line))
						stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
					}
					middleware.ShowErr(err, rw, r, stack)
				}
			} else {
				if !RecoverPanic {
					panic(err)
				} else {
					if ErrorsShow {
						handler := p.getErrorHandler(fmt.Sprint(err))
						handler(rw, r)
						return
					} else {
						Critical("the request url is ", r.URL.Path)
						Critical("Handler crashed with error", err)
						for i := 1; ; i++ {
							_, file, line, ok := runtime.Caller(i)
							if !ok {
								break
							}
							Critical(fmt.Sprintf("%s:%d", file, line))
						}
					}
				}
			}
		}
	}
}
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
}
type responseWriter struct {
	writer  http.ResponseWriter
	started bool
	status  int
}
func (w *responseWriter) Header() http.Header {
	return w.writer.Header()
}
func (w *responseWriter) Write(p []byte) (int, error) {
	w.started = true
	return w.writer.Write(p)
}