• 13.2 自定义路由器设计
    • HTTP路由
    • 默认的路由实现
    • beego框架路由实现
      • 存储路由
      • 静态路由实现
      • 转发路由
      • 使用入门
    • links

    13.2 自定义路由器设计

    HTTP路由

    HTTP路由组件负责将HTTP请求交到对应的函数处理(或者是一个struct的方法),如前面小节所描述的结构图,路由在框架中相当于一个事件处理器,而这个事件包括:

    • 用户请求的路径(path)(例如:/user/123,/article/123),当然还有查询串信息(例如?id=11)
    • HTTP的请求方法(method)(GET、POST、PUT、DELETE、PATCH等)

    路由器就是根据用户请求的事件信息转发到相应的处理函数(控制层)。

    默认的路由实现

    在3.4小节有过介绍Go的http包的详解,里面介绍了Go的http包如何设计和实现路由,这里继续以一个例子来说明:

    1. func fooHandler(w http.ResponseWriter, r *http.Request) {
    2. fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    3. }
    4. http.HandleFunc("/foo", fooHandler)
    5. http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
    6. fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    7. })
    8. log.Fatal(http.ListenAndServe(":8080", nil))

    上面的例子调用了http默认的DefaultServeMux来添加路由,需要提供两个参数,第一个参数是希望用户访问此资源的URL路径(保存在r.URL.Path),第二参数是即将要执行的函数,以提供用户访问的资源。路由的思路主要集中在两点:

    • 添加路由信息
    • 根据用户请求转发到要执行的函数

    Go默认的路由添加是通过函数http.Handlehttp.HandleFunc等来添加,底层都是调用了DefaultServeMux.Handle(pattern string, handler Handler),这个函数会把路由信息存储在一个map信息中map[string]muxEntry,这就解决了上面说的第一点。

    Go监听端口,然后接收到tcp连接会扔给Handler来处理,上面的例子默认nil即为http.DefaultServeMux,通过DefaultServeMux.ServeHTTP函数来进行调度,遍历之前存储的map路由信息,和用户访问的URL进行匹配,以查询对应注册的处理函数,这样就实现了上面所说的第二点。

    1. for k, v := range mux.m {
    2. if !pathMatch(k, path) {
    3. continue
    4. }
    5. if h == nil || len(k) > n {
    6. n = len(k)
    7. h = v.h
    8. }
    9. }

    beego框架路由实现

    目前几乎所有的Web应用路由实现都是基于http默认的路由器,但是Go自带的路由器有几个限制:

    • 不支持参数设定,例如/user/:uid 这种泛类型匹配
    • 无法很好的支持REST模式,无法限制访问的方法,例如上面的例子中,用户访问/foo,可以用GET、POST、DELETE、HEAD等方式访问
    • 一般网站的路由规则太多了,编写繁琐。我前面自己开发了一个API应用,路由规则有三十几条,这种路由多了之后其实可以进一步简化,通过struct的方法进行一种简化

    beego框架的路由器基于上面的几点限制考虑设计了一种REST方式的路由实现,路由设计也是基于上面Go默认设计的两点来考虑:存储路由和转发路由

    存储路由

    针对前面所说的限制点,我们首先要解决参数支持就需要用到正则,第二和第三点我们通过一种变通的方法来解决,REST的方法对应到struct的方法中去,然后路由到struct而不是函数,这样在转发路由的时候就可以根据method来执行不同的方法。

    根据上面的思路,我们设计了两个数据类型controllerInfo(保存路径和对应的struct,这里是一个reflect.Type类型)和ControllerRegistor(routers是一个slice用来保存用户添加的路由信息,以及beego框架的应用信息)

    1. type controllerInfo struct {
    2. regex *regexp.Regexp
    3. params map[int]string
    4. controllerType reflect.Type
    5. }
    6. type ControllerRegistor struct {
    7. routers []*controllerInfo
    8. Application *App
    9. }

    ControllerRegistor对外的接口函数有

    1. func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)

    详细的实现如下所示:

    1. func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
    2. parts := strings.Split(pattern, "/")
    3. j := 0
    4. params := make(map[int]string)
    5. for i, part := range parts {
    6. if strings.HasPrefix(part, ":") {
    7. expr := "([^/]+)"
    8. //a user may choose to override the defult expression
    9. // similar to expressjs: ‘/user/:id([0-9]+)’
    10. if index := strings.Index(part, "("); index != -1 {
    11. expr = part[index:]
    12. part = part[:index]
    13. }
    14. params[j] = part
    15. parts[i] = expr
    16. j++
    17. }
    18. }
    19. //recreate the url pattern, with parameters replaced
    20. //by regular expressions. then compile the regex
    21. pattern = strings.Join(parts, "/")
    22. regex, regexErr := regexp.Compile(pattern)
    23. if regexErr != nil {
    24. //TODO add error handling here to avoid panic
    25. panic(regexErr)
    26. return
    27. }
    28. //now create the Route
    29. t := reflect.Indirect(reflect.ValueOf(c)).Type()
    30. route := &controllerInfo{}
    31. route.regex = regex
    32. route.params = params
    33. route.controllerType = t
    34. p.routers = append(p.routers, route)
    35. }

    静态路由实现

    上面我们实现的动态路由的实现,Go的http包默认支持静态文件处理FileServer,由于我们实现了自定义的路由器,那么静态文件也需要自己设定,beego的静态文件夹路径保存在全局变量StaticDir中,StaticDir是一个map类型,实现如下:

    1. func (app *App) SetStaticPath(url string, path string) *App {
    2. StaticDir[url] = path
    3. return app
    4. }

    应用中设置静态路径可以使用如下方式实现:

    1. beego.SetStaticPath("/img","/static/img")

    转发路由

    转发路由是基于ControllerRegistor里的路由信息来进行转发的,详细的实现如下代码所示:

    1. // AutoRoute
    2. func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    3. defer func() {
    4. if err := recover(); err != nil {
    5. if !RecoverPanic {
    6. // go back to panic
    7. panic(err)
    8. } else {
    9. Critical("Handler crashed with error", err)
    10. for i := 1; ; i += 1 {
    11. _, file, line, ok := runtime.Caller(i)
    12. if !ok {
    13. break
    14. }
    15. Critical(file, line)
    16. }
    17. }
    18. }
    19. }()
    20. var started bool
    21. for prefix, staticDir := range StaticDir {
    22. if strings.HasPrefix(r.URL.Path, prefix) {
    23. file := staticDir + r.URL.Path[len(prefix):]
    24. http.ServeFile(w, r, file)
    25. started = true
    26. return
    27. }
    28. }
    29. requestPath := r.URL.Path
    30. //find a matching Route
    31. for _, route := range p.routers {
    32. //check if Route pattern matches url
    33. if !route.regex.MatchString(requestPath) {
    34. continue
    35. }
    36. //get submatches (params)
    37. matches := route.regex.FindStringSubmatch(requestPath)
    38. //double check that the Route matches the URL pattern.
    39. if len(matches[0]) != len(requestPath) {
    40. continue
    41. }
    42. params := make(map[string]string)
    43. if len(route.params) > 0 {
    44. //add url parameters to the query param map
    45. values := r.URL.Query()
    46. for i, match := range matches[1:] {
    47. values.Add(route.params[i], match)
    48. params[route.params[i]] = match
    49. }
    50. //reassemble query params and add to RawQuery
    51. r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
    52. //r.URL.RawQuery = url.Values(values).Encode()
    53. }
    54. //Invoke the request handler
    55. vc := reflect.New(route.controllerType)
    56. init := vc.MethodByName("Init")
    57. in := make([]reflect.Value, 2)
    58. ct := &Context{ResponseWriter: w, Request: r, Params: params}
    59. in[0] = reflect.ValueOf(ct)
    60. in[1] = reflect.ValueOf(route.controllerType.Name())
    61. init.Call(in)
    62. in = make([]reflect.Value, 0)
    63. method := vc.MethodByName("Prepare")
    64. method.Call(in)
    65. if r.Method == "GET" {
    66. method = vc.MethodByName("Get")
    67. method.Call(in)
    68. } else if r.Method == "POST" {
    69. method = vc.MethodByName("Post")
    70. method.Call(in)
    71. } else if r.Method == "HEAD" {
    72. method = vc.MethodByName("Head")
    73. method.Call(in)
    74. } else if r.Method == "DELETE" {
    75. method = vc.MethodByName("Delete")
    76. method.Call(in)
    77. } else if r.Method == "PUT" {
    78. method = vc.MethodByName("Put")
    79. method.Call(in)
    80. } else if r.Method == "PATCH" {
    81. method = vc.MethodByName("Patch")
    82. method.Call(in)
    83. } else if r.Method == "OPTIONS" {
    84. method = vc.MethodByName("Options")
    85. method.Call(in)
    86. }
    87. if AutoRender {
    88. method = vc.MethodByName("Render")
    89. method.Call(in)
    90. }
    91. method = vc.MethodByName("Finish")
    92. method.Call(in)
    93. started = true
    94. break
    95. }
    96. //if no matches to url, throw a not found exception
    97. if started == false {
    98. http.NotFound(w, r)
    99. }
    100. }

    使用入门

    基于这样的路由设计之后就可以解决前面所说的三个限制点,使用的方式如下所示:

    基本的使用注册路由:

    1. beego.BeeApp.RegisterController("/", &controllers.MainController{})

    参数注册:

    1. beego.BeeApp.RegisterController("/:param", &controllers.UserController{})

    正则匹配:

    1. beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
    • 目录
    • 上一章: 项目规划
    • 下一节: controller设计