Format and remove 13.2.md spaces
This commit is contained in:
350
zh/13.2.md
350
zh/13.2.md
@@ -11,17 +11,17 @@ HTTP路由组件负责将HTTP请求交到对应的函数处理(或者是一个st
|
|||||||
在3.4小节有过介绍Go的http包的详解,里面介绍了Go的http包如何设计和实现路由,这里继续以一个例子来说明:
|
在3.4小节有过介绍Go的http包的详解,里面介绍了Go的http包如何设计和实现路由,这里继续以一个例子来说明:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
func fooHandler(w http.ResponseWriter, r *http.Request) {
|
func fooHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/foo", fooHandler)
|
http.HandleFunc("/foo", fooHandler)
|
||||||
|
|
||||||
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
|
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||||
})
|
})
|
||||||
|
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
|
|
||||||
```
|
```
|
||||||
上面的例子调用了http默认的DefaultServeMux来添加路由,需要提供两个参数,第一个参数是希望用户访问此资源的URL路径(保存在r.URL.Path),第二参数是即将要执行的函数,以提供用户访问的资源。路由的思路主要集中在两点:
|
上面的例子调用了http默认的DefaultServeMux来添加路由,需要提供两个参数,第一个参数是希望用户访问此资源的URL路径(保存在r.URL.Path),第二参数是即将要执行的函数,以提供用户访问的资源。路由的思路主要集中在两点:
|
||||||
@@ -34,15 +34,15 @@ Go默认的路由添加是通过函数`http.Handle`和`http.HandleFunc`等来添
|
|||||||
Go监听端口,然后接收到tcp连接会扔给Handler来处理,上面的例子默认nil即为`http.DefaultServeMux`,通过`DefaultServeMux.ServeHTTP`函数来进行调度,遍历之前存储的map路由信息,和用户访问的URL进行匹配,以查询对应注册的处理函数,这样就实现了上面所说的第二点。
|
Go监听端口,然后接收到tcp连接会扔给Handler来处理,上面的例子默认nil即为`http.DefaultServeMux`,通过`DefaultServeMux.ServeHTTP`函数来进行调度,遍历之前存储的map路由信息,和用户访问的URL进行匹配,以查询对应注册的处理函数,这样就实现了上面所说的第二点。
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
for k, v := range mux.m {
|
for k, v := range mux.m {
|
||||||
if !pathMatch(k, path) {
|
if !pathMatch(k, path) {
|
||||||
continue
|
continue
|
||||||
}
|
|
||||||
if h == nil || len(k) > n {
|
|
||||||
n = len(k)
|
|
||||||
h = v.h
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if h == nil || len(k) > n {
|
||||||
|
n = len(k)
|
||||||
|
h = v.h
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## beego框架路由实现
|
## beego框架路由实现
|
||||||
@@ -60,197 +60,197 @@ beego框架的路由器基于上面的几点限制考虑设计了一种REST方
|
|||||||
根据上面的思路,我们设计了两个数据类型controllerInfo(保存路径和对应的struct,这里是一个reflect.Type类型)和ControllerRegistor(routers是一个slice用来保存用户添加的路由信息,以及beego框架的应用信息)
|
根据上面的思路,我们设计了两个数据类型controllerInfo(保存路径和对应的struct,这里是一个reflect.Type类型)和ControllerRegistor(routers是一个slice用来保存用户添加的路由信息,以及beego框架的应用信息)
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
type controllerInfo struct {
|
type controllerInfo struct {
|
||||||
regex *regexp.Regexp
|
regex *regexp.Regexp
|
||||||
params map[int]string
|
params map[int]string
|
||||||
controllerType reflect.Type
|
controllerType reflect.Type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ControllerRegistor struct {
|
||||||
|
routers []*controllerInfo
|
||||||
|
Application *App
|
||||||
|
}
|
||||||
|
|
||||||
type ControllerRegistor struct {
|
|
||||||
routers []*controllerInfo
|
|
||||||
Application *App
|
|
||||||
}
|
|
||||||
|
|
||||||
```
|
```
|
||||||
ControllerRegistor对外的接口函数有
|
ControllerRegistor对外的接口函数有
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)
|
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)
|
||||||
```
|
```
|
||||||
详细的实现如下所示:
|
详细的实现如下所示:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
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
|
|
||||||
params := make(map[int]string)
|
|
||||||
for i, part := range parts {
|
|
||||||
if strings.HasPrefix(part, ":") {
|
|
||||||
expr := "([^/]+)"
|
|
||||||
|
|
||||||
//a user may choose to override the defult expression
|
j := 0
|
||||||
// similar to expressjs: ‘/user/:id([0-9]+)’
|
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 {
|
if index := strings.Index(part, "("); index != -1 {
|
||||||
expr = part[index:]
|
expr = part[index:]
|
||||||
part = part[:index]
|
part = part[:index]
|
||||||
}
|
|
||||||
params[j] = part
|
|
||||||
parts[i] = expr
|
|
||||||
j++
|
|
||||||
}
|
}
|
||||||
|
params[j] = part
|
||||||
|
parts[i] = expr
|
||||||
|
j++
|
||||||
}
|
}
|
||||||
|
|
||||||
//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
|
|
||||||
t := reflect.Indirect(reflect.ValueOf(c)).Type()
|
|
||||||
route := &controllerInfo{}
|
|
||||||
route.regex = regex
|
|
||||||
route.params = params
|
|
||||||
route.controllerType = t
|
|
||||||
|
|
||||||
p.routers = append(p.routers, route)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//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
|
||||||
|
t := reflect.Indirect(reflect.ValueOf(c)).Type()
|
||||||
|
route := &controllerInfo{}
|
||||||
|
route.regex = regex
|
||||||
|
route.params = params
|
||||||
|
route.controllerType = t
|
||||||
|
|
||||||
|
p.routers = append(p.routers, route)
|
||||||
|
|
||||||
|
}
|
||||||
```
|
```
|
||||||
### 静态路由实现
|
### 静态路由实现
|
||||||
上面我们实现的动态路由的实现,Go的http包默认支持静态文件处理FileServer,由于我们实现了自定义的路由器,那么静态文件也需要自己设定,beego的静态文件夹路径保存在全局变量StaticDir中,StaticDir是一个map类型,实现如下:
|
上面我们实现的动态路由的实现,Go的http包默认支持静态文件处理FileServer,由于我们实现了自定义的路由器,那么静态文件也需要自己设定,beego的静态文件夹路径保存在全局变量StaticDir中,StaticDir是一个map类型,实现如下:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
func (app *App) SetStaticPath(url string, path string) *App {
|
func (app *App) SetStaticPath(url string, path string) *App {
|
||||||
StaticDir[url] = path
|
StaticDir[url] = path
|
||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
应用中设置静态路径可以使用如下方式实现:
|
应用中设置静态路径可以使用如下方式实现:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
beego.SetStaticPath("/img","/static/img")
|
beego.SetStaticPath("/img","/static/img")
|
||||||
|
|
||||||
```
|
```
|
||||||
### 转发路由
|
### 转发路由
|
||||||
转发路由是基于ControllerRegistor里的路由信息来进行转发的,详细的实现如下代码所示:
|
转发路由是基于ControllerRegistor里的路由信息来进行转发的,详细的实现如下代码所示:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
// AutoRoute
|
// AutoRoute
|
||||||
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
if !RecoverPanic {
|
if !RecoverPanic {
|
||||||
// go back to panic
|
// go back to panic
|
||||||
panic(err)
|
panic(err)
|
||||||
} else {
|
} else {
|
||||||
Critical("Handler crashed with error", err)
|
Critical("Handler crashed with error", err)
|
||||||
for i := 1; ; i += 1 {
|
for i := 1; ; i += 1 {
|
||||||
_, file, line, ok := runtime.Caller(i)
|
_, file, line, ok := runtime.Caller(i)
|
||||||
if !ok {
|
if !ok {
|
||||||
break
|
break
|
||||||
}
|
|
||||||
Critical(file, line)
|
|
||||||
}
|
}
|
||||||
|
Critical(file, line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
var started bool
|
|
||||||
for prefix, staticDir := range StaticDir {
|
|
||||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
|
||||||
file := staticDir + r.URL.Path[len(prefix):]
|
|
||||||
http.ServeFile(w, r, file)
|
|
||||||
started = true
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
requestPath := r.URL.Path
|
}()
|
||||||
|
var started bool
|
||||||
//find a matching Route
|
for prefix, staticDir := range StaticDir {
|
||||||
for _, route := range p.routers {
|
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||||
|
file := staticDir + r.URL.Path[len(prefix):]
|
||||||
//check if Route pattern matches url
|
http.ServeFile(w, r, file)
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
params := make(map[string]string)
|
|
||||||
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() + "&" + r.URL.RawQuery
|
|
||||||
//r.URL.RawQuery = url.Values(values).Encode()
|
|
||||||
}
|
|
||||||
//Invoke the request handler
|
|
||||||
vc := reflect.New(route.controllerType)
|
|
||||||
init := vc.MethodByName("Init")
|
|
||||||
in := make([]reflect.Value, 2)
|
|
||||||
ct := &Context{ResponseWriter: w, Request: r, Params: params}
|
|
||||||
in[0] = reflect.ValueOf(ct)
|
|
||||||
in[1] = reflect.ValueOf(route.controllerType.Name())
|
|
||||||
init.Call(in)
|
|
||||||
in = make([]reflect.Value, 0)
|
|
||||||
method := vc.MethodByName("Prepare")
|
|
||||||
method.Call(in)
|
|
||||||
if r.Method == "GET" {
|
|
||||||
method = vc.MethodByName("Get")
|
|
||||||
method.Call(in)
|
|
||||||
} else if r.Method == "POST" {
|
|
||||||
method = vc.MethodByName("Post")
|
|
||||||
method.Call(in)
|
|
||||||
} else if r.Method == "HEAD" {
|
|
||||||
method = vc.MethodByName("Head")
|
|
||||||
method.Call(in)
|
|
||||||
} else if r.Method == "DELETE" {
|
|
||||||
method = vc.MethodByName("Delete")
|
|
||||||
method.Call(in)
|
|
||||||
} else if r.Method == "PUT" {
|
|
||||||
method = vc.MethodByName("Put")
|
|
||||||
method.Call(in)
|
|
||||||
} else if r.Method == "PATCH" {
|
|
||||||
method = vc.MethodByName("Patch")
|
|
||||||
method.Call(in)
|
|
||||||
} else if r.Method == "OPTIONS" {
|
|
||||||
method = vc.MethodByName("Options")
|
|
||||||
method.Call(in)
|
|
||||||
}
|
|
||||||
if AutoRender {
|
|
||||||
method = vc.MethodByName("Render")
|
|
||||||
method.Call(in)
|
|
||||||
}
|
|
||||||
method = vc.MethodByName("Finish")
|
|
||||||
method.Call(in)
|
|
||||||
started = true
|
started = true
|
||||||
break
|
return
|
||||||
}
|
|
||||||
|
|
||||||
//if no matches to url, throw a not found exception
|
|
||||||
if started == false {
|
|
||||||
http.NotFound(w, r)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
requestPath := r.URL.Path
|
||||||
|
|
||||||
|
//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
|
||||||
|
}
|
||||||
|
|
||||||
|
params := make(map[string]string)
|
||||||
|
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() + "&" + r.URL.RawQuery
|
||||||
|
//r.URL.RawQuery = url.Values(values).Encode()
|
||||||
|
}
|
||||||
|
//Invoke the request handler
|
||||||
|
vc := reflect.New(route.controllerType)
|
||||||
|
init := vc.MethodByName("Init")
|
||||||
|
in := make([]reflect.Value, 2)
|
||||||
|
ct := &Context{ResponseWriter: w, Request: r, Params: params}
|
||||||
|
in[0] = reflect.ValueOf(ct)
|
||||||
|
in[1] = reflect.ValueOf(route.controllerType.Name())
|
||||||
|
init.Call(in)
|
||||||
|
in = make([]reflect.Value, 0)
|
||||||
|
method := vc.MethodByName("Prepare")
|
||||||
|
method.Call(in)
|
||||||
|
if r.Method == "GET" {
|
||||||
|
method = vc.MethodByName("Get")
|
||||||
|
method.Call(in)
|
||||||
|
} else if r.Method == "POST" {
|
||||||
|
method = vc.MethodByName("Post")
|
||||||
|
method.Call(in)
|
||||||
|
} else if r.Method == "HEAD" {
|
||||||
|
method = vc.MethodByName("Head")
|
||||||
|
method.Call(in)
|
||||||
|
} else if r.Method == "DELETE" {
|
||||||
|
method = vc.MethodByName("Delete")
|
||||||
|
method.Call(in)
|
||||||
|
} else if r.Method == "PUT" {
|
||||||
|
method = vc.MethodByName("Put")
|
||||||
|
method.Call(in)
|
||||||
|
} else if r.Method == "PATCH" {
|
||||||
|
method = vc.MethodByName("Patch")
|
||||||
|
method.Call(in)
|
||||||
|
} else if r.Method == "OPTIONS" {
|
||||||
|
method = vc.MethodByName("Options")
|
||||||
|
method.Call(in)
|
||||||
|
}
|
||||||
|
if AutoRender {
|
||||||
|
method = vc.MethodByName("Render")
|
||||||
|
method.Call(in)
|
||||||
|
}
|
||||||
|
method = vc.MethodByName("Finish")
|
||||||
|
method.Call(in)
|
||||||
|
started = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
//if no matches to url, throw a not found exception
|
||||||
|
if started == false {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
### 使用入门
|
### 使用入门
|
||||||
基于这样的路由设计之后就可以解决前面所说的三个限制点,使用的方式如下所示:
|
基于这样的路由设计之后就可以解决前面所说的三个限制点,使用的方式如下所示:
|
||||||
@@ -258,17 +258,17 @@ ControllerRegistor对外的接口函数有
|
|||||||
基本的使用注册路由:
|
基本的使用注册路由:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
beego.BeeApp.RegisterController("/", &controllers.MainController{})
|
beego.BeeApp.RegisterController("/", &controllers.MainController{})
|
||||||
```
|
```
|
||||||
参数注册:
|
参数注册:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
|
beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
|
||||||
```
|
```
|
||||||
正则匹配:
|
正则匹配:
|
||||||
```Go
|
```Go
|
||||||
|
|
||||||
beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
|
beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
|
||||||
```
|
```
|
||||||
## links
|
## links
|
||||||
* [目录](<preface.md>)
|
* [目录](<preface.md>)
|
||||||
|
|||||||
Reference in New Issue
Block a user