简介
官方——https://github.com/julienschmidt/httprouter
HttpRouter is a lightweight high performance HTTP request router (also
called multiplexer or just mux for short) for Go.In contrast to the default mux of Go’s net/http package, this router
supports variables in the routing pattern and matches against the
request method. It also scales better.The router is optimized for high performance and a small memory
footprint. It scales well even with very long paths and a large number
of routes. A compressing dynamic trie (radix tree) structure is used
for efficient matching.
简单描述,httprouter是一个golang实现的路由组件。httprouter使用一个前缀树来维护映射的父子关系,通过前缀树快速路由。同时其里面的HttpRouter结构体实现了golang的net.http.server的Handler接口,可以作为httpHandle发布。golang以性能出名的gin使用的也就是httprouter来做路由处理。
依赖
require github.com/julienschmidt/httprouter latest
使用Demo
package httpRouterDemo
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Write([]byte("hello world"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
http.ListenAndServe(":80", router)
}
源码分析
New方法实际就是生成一个HttpRouter对象
接下来看看注册Get映射的实现
func (r *Router) GET(path string, handle Handle) {
r.Handle(http.MethodGet, path, handle)
}
func (r *Router) Handle(method, path string, handle Handle) {
if len(path) < 1 || path[0] != '/' {
panic("path must begin with '/' in path '" + path + "'")
}
if r.trees == nil {
r.trees = make(map[string]*node)
}
root := r.trees[method]
if root == nil {
root = new(node)
r.trees[method] = root
r.globalAllowed = r.allowed("*", "")
}
root.addRoute(path, handle)
}
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 nu