一个简单示例

在真正开启本章的核心内容之前,我们先来看一个简单的动态路由使用示例:

以上示例中展示了gf框架支持的三种模糊匹配路由规则,:name*any{field}分别表示命名匹配规则、模糊匹配规则及字段匹配规则。不同的规则中使用/符号来划分层级,路由检索采用深度优先算法,层级越深的规则优先级也会越高。我们运行以上示例,通过访问几个URL来看看效果:

  1. URL 结果
  2. http://127.0.0.1:8199/user/list/2.html /user/list/{field}.html
  3. http://127.0.0.1:8199/user/update /:name/update
  4. http://127.0.0.1:8199/user/info /:name/:action
  5. http://127.0.0.1:8199/user /:name/*any

在这个示例中我们也可以看到,由于优先级的限制,路由规则/:name会被/:name/*any规则覆盖,将会无法被匹配到,所以在分配路由规则的时候,需要进行统一规划和管理,避免类似情况的产生。

路由注册规则

我们来看一下之前一直使用的BindHandler的原型:

  1. func (s *Server) BindHandler(pattern string, handler HandlerFunc) error

该方法是路由注册的最基础方法,其中的pattern为路由注册规则字符串,在其他路由注册方法中也会使用到,参数格式如下:

  1. [HTTPMethod:]路由规则[@域名]

其中HTTPMethod(支持的Method:GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE)和@域名为非必需参数,一般来说直接给定路由规则参数即可,BindHandler会自动绑定所有的请求方式,如果给定HTTPMethod,那么路由规则仅会在该请求方式下有效。@域名可以指定生效的域名名称,那么该路由规则仅会在该域名下生效。

我们来看一个例子:

  1. package main
  2. import (
  3. "github.com/gogf/gf/net/ghttp"
  4. )
  5. func main() {
  6. s := g.Server()
  7. // 该路由规则仅会在GET请求下有效
  8. r.Response.WriteJson(r.Router)
  9. })
  10. // 该路由规则仅会在GET请求及localhost域名下有效
  11. s.BindHandler("GET:/order/info/{order_id}@localhost", func(r *ghttp.Request){
  12. r.Response.WriteJson(r.Router)
  13. })
  14. // 该路由规则仅会在DELETE请求下有效
  15. s.BindHandler("DELETE:/comment/{id}", func(r *ghttp.Request){
  16. r.Response.WriteJson(r.Router)
  17. })
  18. s.SetPort(8199)
  19. s.Run()
  20. }

其中返回的参数r.Router是当前匹配的路由规则信息,访问当该方法的时候,服务端会输出当前匹配的路由规则信息。执行后,我们在终端使用curl命令进行测试:

  1. $ curl -XGET http://127.0.0.1:8199/order/list/1.html
  2. $ curl -XGET http://127.0.0.1:8199/order/info/1
  3. Not Found
  4. $ curl -XGET http://localhost:8199/order/info/1
  5. {"Domain":"localhost","Method":"GET","Priority":3,"Uri":"/order/info/{order_id}"}
  6. $ curl -XDELETE http://127.0.0.1:8199/comment/1000
  7. {"Domain":"default","Method":"DELETE","Priority":2,"Uri":"/comment/{id}"}
  8. $ curl -XGET http://127.0.0.1:8199/comment/1000
  9. Not Found

动态路由规则

动态路由规则分为三种:命名匹配规则模糊匹配规则字段匹配规则。动态路由的底层数据结构是由树形哈希表双向链表构建的,树形哈希表便于高效率地层级匹配URI;数据链表用于优先级控制,同一层级的路由规则按照优先级进行排序,优先级高的规则排在链表头。底层的路由规则与请求URI的匹配计算采用的是正则表达式,并充分使用了缓存机制,执行效率十分高效(具体算法细节详见后续章节)。

所有匹配到的参数都将会以Router参数的形式传递给业务层,可以通过ghttp.Request对象的以下方法获取:

也可以使用ghttp.Request.Get*方式进行获取。

精准匹配规则即未使用任何动态规则的规则,如:userorderinfo等等这种确定名称的规则。在大多数场景下,精准匹配规则会和动态规则一起使用来进行路由注册(例如:/:name/list,其中层级1:name为命名匹配规则,层级2list是精准匹配规则)。

使用:name方式进行匹配(name为自定义的匹配名称),对URI指定层级的参数进行命名匹配(类似正则([^/]+),该URI层级必须有值),对应匹配参数会被解析为Router参数并传递给注册的服务接口使用。

匹配示例1:

  1. rule: /user/:user
  2. /user/john match
  3. /user/you match
  4. /user/john/profile no match
  5. /user/ no match

匹配示例2:

rule: /:name/action

/john/name                no match
/john/action              match
/smith/info               no match
/smith/info/age           no match
/smith/action             match

匹配示例3:

rule: /:name/:action

/john/name                match
/john/info                match
/smith/info               match
/smith/info/age           no match
/smith/action/del         no match

使用*any方式进行匹配(any为自定义的匹配名称),对URI指定位置之后的参数进行模糊匹配(类似正则(.*),该URI层级可以为空),并将匹配参数解析为Router参数并传递给注册的服务接口使用。

rule: /src/*path

/src/                     match
/src/somefile.go          match
/src/subdir/somefile.go   match
/user/                    no match
/user/john                no match

匹配示例2:

rule: /src/*path/:action

/src/                     no match
/src/somefile.go          match
/src/somefile.go/del      match
/src/subdir/file.go/del   match

匹配示例3:

使用{field}方式进行匹配(field为自定义的匹配名称),可对URI任意位置的参数进行截取匹配(类似正则([\w\.\-]+),该URI层级必须有值,并且可以在同一层级进行多个字段匹配),并将匹配参数解析为Router参数并传递给注册的服务接口使用。

匹配示例1:

rule: /order/list/{page}.php

/order/list/1.php          match
/order/list/666.php        match
/order/list/2.php5         no match
/order/list/1              no match
/order/list                no match

匹配示例2:

rule: /db-{table}/{id}

/db-user/1                     match
/db-user/2                     match
/db/user/1                     no match
/db-order/100                  match
/database-order/100            no match

匹配示例3:

rule: /{obj}-{act}/*param

/user-delete/10                match
/order-update/20               match
/log-list                      match
/log/list/1                    no match
/comment/delete/10             no match
package main

import (
    "github.com/gogf/gf/net/ghttp"
    "github.com/gogf/gf/frame/g"
)

func main() {
    s := g.Server()
    // 一个简单的分页路由示例
    s.BindHandler("/user/list/{page}.html", func(r *ghttp.Request){
        r.Response.Writeln(r.Get("page"))
    })
    // {xxx} 规则与 :xxx 规则混合使用
    s.BindHandler("/{object}/:attr/{act}.php", func(r *ghttp.Request){
        r.Response.Writeln(r.Get("object"))
        r.Response.Writeln(r.Get("attr"))
        r.Response.Writeln(r.Get("act"))
    })
    // 多种模糊匹配规则混合使用
    s.BindHandler("/{class}-{course}/:name/*act", func(r *ghttp.Request){
        r.Response.Writeln(r.Get("class"))
        r.Response.Writeln(r.Get("course"))
        r.Response.Writeln(r.Get("name"))
        r.Response.Writeln(r.Get("act"))
    })
    s.SetPort(8199)
    s.Run()
}

执行后,我们可以通过curl命令或者浏览器访问的方式进行测试,以下为测试结果:


路由优先级控制

优先级控制按照深度优先策略,最主要的几点因素:

  1. 层级越深的规则优先级越高
  2. 同一层级下,精准匹配优先级高于模糊匹配

我们来看示例(左边的规则优先级比右边高):