1
0
mirror of https://github.com/astaxie/beego.git synced 2024-06-02 12:03:27 +00:00
This commit is contained in:
astaxie 2012-12-18 15:18:43 +08:00
parent d562687868
commit 8a99591298

567
router.go
View File

@ -1,283 +1,284 @@
package beego package beego
import ( import (
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
"regexp" "regexp"
"runtime" "runtime"
"strings" "strings"
) )
type controllerInfo struct { type controllerInfo struct {
pattern string pattern string
regex *regexp.Regexp regex *regexp.Regexp
params map[int]string params map[int]string
controllerType reflect.Type controllerType reflect.Type
} }
type ControllerRegistor struct { type ControllerRegistor struct {
routers []*controllerInfo routers []*controllerInfo
fixrouters []*controllerInfo fixrouters []*controllerInfo
filters []http.HandlerFunc filters []http.HandlerFunc
} }
func NewControllerRegistor() *ControllerRegistor { func NewControllerRegistor() *ControllerRegistor {
return &ControllerRegistor{routers: make([]*controllerInfo, 0)} return &ControllerRegistor{routers: make([]*controllerInfo, 0)}
} }
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) { func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
parts := strings.Split(pattern, "/") parts := strings.Split(pattern, "/")
j := 0 j := 0
params := make(map[int]string) params := make(map[int]string)
for i, part := range parts { for i, part := range parts {
if strings.HasPrefix(part, ":") { if strings.HasPrefix(part, ":") {
expr := "([^/]+)" expr := "([^/]+)"
//a user may choose to override the defult expression //a user may choose to override the defult expression
// similar to expressjs: /user/:id([0-9]+) // similar to expressjs: /user/:id([0-9]+)
if index := strings.Index(part, "("); index != -1 { if index := strings.Index(part, "("); index != -1 {
expr = part[index:] expr = part[index:]
part = part[:index] part = part[:index]
} }
params[j] = part params[j] = part
parts[i] = expr parts[i] = expr
j++ j++
} }
} }
if j == 0 { if j == 0 {
//now create the Route //now create the Route
t := reflect.Indirect(reflect.ValueOf(c)).Type() t := reflect.Indirect(reflect.ValueOf(c)).Type()
route := &controllerInfo{} route := &controllerInfo{}
route.pattern = pattern route.pattern = pattern
route.controllerType = t route.controllerType = t
p.fixrouters = append(p.fixrouters, route) p.fixrouters = append(p.fixrouters, route)
} else { // add regexp routers } else { // add regexp routers
//recreate the url pattern, with parameters replaced //recreate the url pattern, with parameters replaced
//by regular expressions. then compile the regex //by regular expressions. then compile the regex
pattern = strings.Join(parts, "/") pattern = strings.Join(parts, "/")
regex, regexErr := regexp.Compile(pattern) regex, regexErr := regexp.Compile(pattern)
if regexErr != nil { if regexErr != nil {
//TODO add error handling here to avoid panic //TODO add error handling here to avoid panic
panic(regexErr) panic(regexErr)
return return
} }
//now create the Route //now create the Route
t := reflect.Indirect(reflect.ValueOf(c)).Type() t := reflect.Indirect(reflect.ValueOf(c)).Type()
route := &controllerInfo{} route := &controllerInfo{}
route.regex = regex route.regex = regex
route.params = params route.params = params
route.controllerType = t route.pattern = pattern
route.controllerType = t
p.routers = append(p.routers, route)
} p.routers = append(p.routers, route)
}
}
}
// Filter adds the middleware filter.
func (p *ControllerRegistor) Filter(filter http.HandlerFunc) { // Filter adds the middleware filter.
p.filters = append(p.filters, filter) func (p *ControllerRegistor) Filter(filter http.HandlerFunc) {
} p.filters = append(p.filters, filter)
}
// FilterParam adds the middleware filter if the REST URL parameter exists.
func (p *ControllerRegistor) FilterParam(param string, filter http.HandlerFunc) { // FilterParam adds the middleware filter if the REST URL parameter exists.
if !strings.HasPrefix(param, ":") { func (p *ControllerRegistor) FilterParam(param string, filter http.HandlerFunc) {
param = ":" + param if !strings.HasPrefix(param, ":") {
} param = ":" + param
}
p.Filter(func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Query().Get(param) p.Filter(func(w http.ResponseWriter, r *http.Request) {
if len(p) > 0 { p := r.URL.Query().Get(param)
filter(w, r) if len(p) > 0 {
} filter(w, r)
}) }
} })
}
// FilterPrefixPath adds the middleware filter if the prefix path exists.
func (p *ControllerRegistor) FilterPrefixPath(path string, filter http.HandlerFunc) { // FilterPrefixPath adds the middleware filter if the prefix path exists.
p.Filter(func(w http.ResponseWriter, r *http.Request) { func (p *ControllerRegistor) FilterPrefixPath(path string, filter http.HandlerFunc) {
if strings.HasPrefix(r.URL.Path, path) { p.Filter(func(w http.ResponseWriter, r *http.Request) {
filter(w, r) if strings.HasPrefix(r.URL.Path, path) {
} filter(w, r)
}) }
} })
}
// AutoRoute
func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) { // AutoRoute
defer func() { func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if err := recover(); err != nil { defer func() {
if !RecoverPanic { if err := recover(); err != nil {
// go back to panic if !RecoverPanic {
panic(err) // go back to panic
} else { panic(err)
Critical("Handler crashed with error", err) } else {
for i := 1; ; i += 1 { Critical("Handler crashed with error", err)
_, file, line, ok := runtime.Caller(i) for i := 1; ; i += 1 {
if !ok { _, file, line, ok := runtime.Caller(i)
break if !ok {
} break
Critical(file, line) }
} Critical(file, line)
} }
} }
}() }
w := &responseWriter{writer: rw} }()
w := &responseWriter{writer: rw}
var runrouter *controllerInfo
var findrouter bool var runrouter *controllerInfo
var findrouter bool
params := make(map[string]string)
params := make(map[string]string)
//static file server
for prefix, staticDir := range StaticDir { //static file server
if strings.HasPrefix(r.URL.Path, prefix) { for prefix, staticDir := range StaticDir {
file := staticDir + r.URL.Path[len(prefix):] if strings.HasPrefix(r.URL.Path, prefix) {
http.ServeFile(w, r, file) file := staticDir + r.URL.Path[len(prefix):]
w.started = true http.ServeFile(w, r, file)
return w.started = true
} return
} }
}
requestPath := r.URL.Path
requestPath := r.URL.Path
//first find path from the fixrouters to Improve Performance
for _, route := range p.fixrouters { //first find path from the fixrouters to Improve Performance
n := len(requestPath) for _, route := range p.fixrouters {
if (requestPath[n-1] != '/' && route.pattern == requestPath) || n := len(requestPath)
(len(route.pattern) >= n && requestPath[0:n] == route.pattern) { if (requestPath[n-1] != '/' && route.pattern == requestPath) ||
runrouter = route (len(route.pattern) >= n && requestPath[0:n-1] == route.pattern) {
findrouter = true runrouter = route
break findrouter = true
} break
} }
}
if !findrouter {
//find a matching Route if !findrouter {
for _, route := range p.routers { //find a matching Route
for _, route := range p.routers {
//check if Route pattern matches url
if !route.regex.MatchString(requestPath) { //check if Route pattern matches url
continue if !route.regex.MatchString(requestPath) {
} continue
}
//get submatches (params)
matches := route.regex.FindStringSubmatch(requestPath) //get submatches (params)
matches := route.regex.FindStringSubmatch(requestPath)
//double check that the Route matches the URL pattern.
if len(matches[0]) != len(requestPath) { //double check that the Route matches the URL pattern.
continue if len(matches[0]) != len(requestPath) {
} continue
}
if len(route.params) > 0 {
//add url parameters to the query param map if len(route.params) > 0 {
values := r.URL.Query() //add url parameters to the query param map
for i, match := range matches[1:] { values := r.URL.Query()
values.Add(route.params[i], match) for i, match := range matches[1:] {
params[route.params[i]] = match 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() + "&" + r.URL.RawQuery //reassemble query params and add to RawQuery
//r.URL.RawQuery = url.Values(values).Encode() r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
} //r.URL.RawQuery = url.Values(values).Encode()
runrouter = route }
findrouter = true runrouter = route
break findrouter = true
} break
} }
}
if runrouter != nil {
//execute middleware filters if runrouter != nil {
for _, filter := range p.filters { //execute middleware filters
filter(w, r) for _, filter := range p.filters {
if w.started { filter(w, r)
return if w.started {
} return
} }
}
//Invoke the request handler
vc := reflect.New(runrouter.controllerType) //Invoke the request handler
vc := reflect.New(runrouter.controllerType)
//call the controller init function
init := vc.MethodByName("Init") //call the controller init function
in := make([]reflect.Value, 2) init := vc.MethodByName("Init")
ct := &Context{ResponseWriter: w, Request: r, Params: params} in := make([]reflect.Value, 2)
in[0] = reflect.ValueOf(ct) ct := &Context{ResponseWriter: w, Request: r, Params: params}
in[1] = reflect.ValueOf(runrouter.controllerType.Name()) in[0] = reflect.ValueOf(ct)
init.Call(in) in[1] = reflect.ValueOf(runrouter.controllerType.Name())
//call prepare function init.Call(in)
in = make([]reflect.Value, 0) //call prepare function
method := vc.MethodByName("Prepare") in = make([]reflect.Value, 0)
method.Call(in) method := vc.MethodByName("Prepare")
method.Call(in)
//if response has written,yes don't run next
if !w.started { //if response has written,yes don't run next
if r.Method == "GET" { if !w.started {
method = vc.MethodByName("Get") if r.Method == "GET" {
method.Call(in) method = vc.MethodByName("Get")
} else if r.Method == "POST" { method.Call(in)
method = vc.MethodByName("Post") } else if r.Method == "POST" {
method.Call(in) method = vc.MethodByName("Post")
} else if r.Method == "HEAD" { method.Call(in)
method = vc.MethodByName("Head") } else if r.Method == "HEAD" {
method.Call(in) method = vc.MethodByName("Head")
} else if r.Method == "DELETE" { method.Call(in)
method = vc.MethodByName("Delete") } else if r.Method == "DELETE" {
method.Call(in) method = vc.MethodByName("Delete")
} else if r.Method == "PUT" { method.Call(in)
method = vc.MethodByName("Put") } else if r.Method == "PUT" {
method.Call(in) method = vc.MethodByName("Put")
} else if r.Method == "PATCH" { method.Call(in)
method = vc.MethodByName("Patch") } else if r.Method == "PATCH" {
method.Call(in) method = vc.MethodByName("Patch")
} else if r.Method == "OPTIONS" { method.Call(in)
method = vc.MethodByName("Options") } else if r.Method == "OPTIONS" {
method.Call(in) method = vc.MethodByName("Options")
} method.Call(in)
if !w.started { }
if AutoRender { if !w.started {
method = vc.MethodByName("Render") if AutoRender {
method.Call(in) method = vc.MethodByName("Render")
} method.Call(in)
if !w.started { }
method = vc.MethodByName("Finish") if !w.started {
method.Call(in) method = vc.MethodByName("Finish")
} method.Call(in)
} }
} }
} }
}
//if no matches to url, throw a not found exception
if w.started == false { //if no matches to url, throw a not found exception
http.NotFound(w, r) if w.started == false {
} http.NotFound(w, r)
} }
}
//responseWriter is a wrapper for the http.ResponseWriter
//started set to true if response was written to then don't execute other handler //responseWriter is a wrapper for the http.ResponseWriter
type responseWriter struct { //started set to true if response was written to then don't execute other handler
writer http.ResponseWriter type responseWriter struct {
started bool writer http.ResponseWriter
status int started bool
} status int
}
// Header returns the header map that will be sent by WriteHeader.
func (w *responseWriter) Header() http.Header { // Header returns the header map that will be sent by WriteHeader.
return w.writer.Header() 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 // Write writes the data to the connection as part of an HTTP reply,
func (w *responseWriter) Write(p []byte) (int, error) { // and sets `started` to true
w.started = true func (w *responseWriter) Write(p []byte) (int, error) {
return w.writer.Write(p) w.started = true
} return w.writer.Write(p)
}
// WriteHeader sends an HTTP response header with status code,
// and sets `started` to true // WriteHeader sends an HTTP response header with status code,
func (w *responseWriter) WriteHeader(code int) { // and sets `started` to true
w.status = code func (w *responseWriter) WriteHeader(code int) {
w.started = true w.status = code
w.writer.WriteHeader(code) w.started = true
} w.writer.WriteHeader(code)
}