Golang httprouter 源码阅读

一、httprouter特点介绍

  • 轻量、高性能的route框架
  • 显示匹配
  • 不关注请求路径尾部 \
  • 路径自动矫正
  • 支持url参数
  • 零字节垃圾
  • 性能优越
  • 不会服务器崩溃
  • 完美的API支持

二、httprouter如何工作

此路由器依赖大量使用公共前缀的树形结构,它是基于压缩前缀树或者叫基数树。有共同父元素的节点有相同前缀。以下是GET请求方法树结构的样子:

Priority   Path             Handle
9          \                *<1>
3          ├s               nil
2          |├earch\         *<2>
1          |└upport\        *<3>
2          ├blog\           *<4>
1          |    └:post      nil
1          |         └\     *<5>
2          ├about-us\       *<6>
1          |        └team\  *<7>
1          └contact\        *<8>

// 这个图相当于注册了下面这几个路由
GET("/search/", func1)
GET("/support/", func2)
GET("/blog/:post/", func3)
GET("/about-us/", func4)
GET("/about-us/team/", func5)
GET("/contact/", func6)

每个* 代表一个handler function的内存地址。如果你跟踪这颗树的根节点到叶子节点,你会得到完整的路由路径,例如:\blog:post\,在这里:post只是一个占位符,它实际上是一个文章的名称。不像hash-map,这种树形结构允许我们使用动态参数例如:post,因为httprouter是直接与请求路径匹配而不是匹配路径的哈希值。在benchmarks的测试中展现出httprouter非常高效。

因为url路径是分层结构,并且使用的字符集是有限的,所以它们很可能有很多公共的前缀。这样就可以使我们减少路由到更小的问题中。而且此路由器还对每种请求方法都有一颗树。首先它比每个节点都保存handle要更节省空间,并且在前缀树开始查询会较少很多问题。

为了更好的伸缩性,在每个树层级上,子节点都通过优先级排序,这里的优先级是注册在此节点的handle的数量(子,孙等等往下的节点):

  1. 有最多路由路径的节点先被搜索。这样可以帮助尽可能快的搜索到handle。
  2. 这比较像成本补偿,最长可达路径总是优先被搜索。以下是可视化的树形结构,节点的搜索顺序为从上到下,从左到右。
    ├------------
    ├---------
    ├-----
    ├----
    ├--
    ├--
    └-
    

三、httprouter如何初始化(构造树结构)

route框架最重要就是两点,一是如何初始化,二是用户请求来后如何分发(其他比如中间件也是一些重要的点)。
先从官方的server demo看如何初始化:

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

这里从httprouter.New()跟踪进去可以发现两个重要的struct,一个是Router,一个是node。
先看一下Router

// Router 是一个 http.Handler 可以通过定义的路由将请求分发给不同的函数
type Router struct {
    trees map[string]*node

    // 这个参数是否自动处理当访问路径最后带的 /,一般为 true 就行。
    // 例如: 当访问 /foo/ 时, 此时没有定义 /foo/ 这个路由,但是定义了 
    // /foo 这个路由,就对自动将 /foo/ 重定向到 /foo (GET 请求
    // 是 http 301 重定向,其他方式的请求是 http 307 重定向)。
    RedirectTrailingSlash bool

    // 是否自动修正路径, 如果路由没有找到时,Router 会自动尝试修复。
    // 首先删除多余的路径,像 ../ 或者 // 会被删除。
    // 然后将清理过的路径再不区分大小写查找,如果能够找到对应的路由, 将请求重定向到
    // 这个路由上 ( GET 是 301, 其他是 307 ) 。
    RedirectFixedPath bool

    // 用来配合下面的 MethodNotAllowed 参数。 
    HandleMethodNotAllowed bool

    // 如果为 true ,会自动回复 OPTIONS 方式的请求。
    // 如果自定义了 OPTIONS 路由,会使用自定义的路由,优先级高于这个自动回复。
    HandleOPTIONS bool

    // 路由没有匹配上时调用这个 handler 。
    // 如果没有定义这个 handler ,就会返回标准库中的 http.NotFound 。
    NotFound http.Handler

    // 当一个请求是不被允许的,并且上面的 HandleMethodNotAllowed 设置为 ture 的时候,
    // 如果这个参数没有设置,将使用状态为 with http.StatusMethodNotAllowed 的 http.Error
    // 在 handler 被调用以前,为允许请求的方法设置 "Allow" header 。
    MethodNotAllowed http.Handler

    // 当出现 panic 的时候,通过这个函数来恢复。会返回一个错误码为 500 的 http error 
    // (Internal Server Error) ,这个函数是用来保证出现 painc 服务器不会崩溃。
    PanicHandler func(http.ResponseWriter, *http.Request, interface{})
}

再看node

type node struct {
    // 当前节点的 URL 路径
    // 如上面图中的例子的首先这里是一个 /
    // 然后 children 中会有 path 为 [s, blog ...] 等的节点 
    // 然后 s 还有 children node [earch,upport] 等,就不再说明了
    path      string

    // 判断当前节点路径是不是含有参数的节点, 上图中的 :post 的上级 blog 就是wildChild节点
    wildChild bool

    // 节点类型: static, root, param, catchAll
    // static: 静态节点, 如上图中的父节点 s (不包含 handler 的)
    // root: 如果插入的节点是第一个, 那么是root节点
    // catchAll: 有*匹配的节点
    // param: 参数节点,比如上图中的 :post 节点
    nType     nodeType

    // path 中的参数最大数量,最大只能保存 255 个(超过这个的情况貌似太难见到了)
    // 这里是一个非负的 8 进制数字,最大也只能是 255 了
    maxParams uint8

    // 和下面的 children 对应,保留的子节点的第一个字符
    // 如上图中的 s 节点,这里保存的就是 eu (earch 和 upport)的首字母 
    indices   string

    // 当前节点的所有直接子节点
    children  []*node

    // 当前节点对应的 handler
    handle    Handle

    // 优先级,查找的时候会用到,表示当前节点加上所有子节点的数目
    priority  uint32
}

从httprouter.New()方法进入可以看到

func (r *Router) GET(path string, handle Handle) {
	r.Handle("GET", path, handle)
}

func (r *Router) Handle(method, path string, handle Handle) {
	if path[0] != '/' {
		panic("path must begin with '/' in path '" + path + "'")
	}

	if r.trees == nil {
		r.trees = make(map[string]*node)
	}

	// 从这里可以看出每种http方法(也可以是自定义的方法)都在同一颗树,作为不同根节点。
	root := r.trees[method]
	if root == nil {
		// 初始化各个方法的根节点
		root = new(node)
		r.trees[method] = root
	}
	// addRoute方法是把handle添加到路径对应的节点上
	root.addRoute(path, handle)
}

接着看addRoute

func (n *node) addRoute(path string, handle Handle) {
	fullPath := path
	n.priority++
	numParams := countParams(path)

	// non-empty tree
	if len(n.path) > 0 || len(n.children) > 0 {
	walk:
		for {
			// Update maxParams of the current node
			if numParams > n.maxParams {
				n.maxParams = numParams
			}

			// Find the longest common prefix.
			// This also implies that the common prefix contains no ':' or '*'
			// since the existing key can't contain those chars.
			i := 0
			max := min(len(path), len(n.path))
			for i < max && path[i] == n.path[i] {
				i++
			}

			// Split edge
			if i < len(n.path) {
				child := node{
					path:      n.path[i:],
					wildChild: n.wildChild,
					nType:     static,
					indices:   n.indices,
					children:  n.children,
					handle:    n.handle,
					priority:  n.priority - 1,
				}

				// Update maxParams (max of all children)
				for i := range child.children {
					if child.children[i].maxParams > child.maxParams {
						child.maxParams = child.children[i].maxParams
					}
				}

				n.children = []*node{&child}
				// []byte for proper unicode char conversion, see #65
				n.indices = string([]byte{n.path[i]})
				n.path = path[:i]
				n.handle = nil
				n.wildChild = false
			}

			// Make new node a child of this node
			if i < len(path) {
				path = path[i:]

				if n.wildChild {
					n = n.children[0]
					n.priority++

					// Update maxParams of the child node
					if numParams > n.maxParams {
						n.maxParams = numParams
					}
					numParams--

					// Check if the wildcard matches
					if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
						// Check for longer wildcard, e.g. :name and :names
						(len(n.path) >= len(path) || path[len(n.path)] == '/') {
						continue walk
					} else {
						// Wildcard conflict
						var pathSeg string
						if n.nType == catchAll {
							pathSeg = path
						} else {
							pathSeg = strings.SplitN(path, "/", 2)[0]
						}
						prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
						panic("'" + pathSeg +
							"' in new path '" + fullPath +
							"' conflicts with existing wildcard '" + n.path +
							"' in existing prefix '" + prefix +
							"'")
					}
				}

				c := path[0]

				// slash after param
				if n.nType == param && c == '/' && len(n.children) == 1 {
					n = n.children[0]
					n.priority++
					continue walk
				}

				// Check if a child with the next path byte exists
				for i := 0; i < len(n.indices); i++ {
					if c == n.indices[i] {
						i = n.incrementChildPrio(i)
						n = n.children[i]
						continue walk
					}
				}

				// Otherwise insert it
				if c != ':' && c != '*' {
					// []byte for proper unicode char conversion, see #65
					n.indices += string([]byte{c})
					child := &node{
						maxParams: numParams,
					}
					n.children = append(n.children, child)
					n.incrementChildPrio(len(n.indices) - 1)
					n = child
				}
				n.insertChild(numParams, path, fullPath, handle)
				return

			} else if i == len(path) { // Make node a (in-path) leaf
				if n.handle != nil {
					panic("a handle is already registered for path '" + fullPath + "'")
				}
				n.handle = handle
			}
			return
		}
	} else { // Empty tree
		n.insertChild(numParams, path, fullPath, handle)
		n.nType = root
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章