Httprouter源码学习

Httprouter是一个高性能的HTTP请求路由器,支持路由模式中的变量和请求方法匹配。它使用压缩的动态前缀树实现高效匹配,并以其高性能和小内存占用著称。本文将介绍其依赖、使用示例及源码分析。
摘要由CSDN通过智能技术生成

Httprouter源码学习

简介

官方——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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值