面经-gin路由

189 阅读1分钟
  • 实现原理:gin框架中的路由基于httprouter做的,使用了一个前缀树来管理请求url

7e19a36f9722418bb4806a2f5dfdf09c_tplv-k3u1fbpfcp-zoom-in-crop-mark_3024_0_0_0.webp

  • httprouter会对每种http方法生成一颗前缀树,树由一个个节点构成
GET    /user/{userID} HTTP/1.1
POST   /user/{userID} HTTP/1.1
PUT    /user/{userID} HTTP/1.1
DELETE /user/{userID} HTTP/1.1

如这四个请求,分别会注册四颗路由树出来。

func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
    //....
    root := engine.trees.get(method)
    if root == nil {
        root = new(node)
        root.fullPath = "/"
        engine.trees = append(engine.trees, methodTree{method: method, root: root})
    }
    root.addRoute(path, handlers)
    // ...
}
  • 拿到一个 method 方法时,去 trees slice 中遍历
  • 如果 trees slice 存在这个 method, 则这个URL对应的 handler 直接添加到找到的路由树上
  • 如果没有找到,则重新创建一颗新的方法树出来, 然后将 URL对应的 handler 添加到这个路由 树上
  • 当客户端请求时,去路由树里面匹配url,找到对应的handler---handlehttprequest要做的