mux库源码分析

本文深入分析Go语言中的mux库,详细解释了mux如何实现轻量级路由,包括基于host、path和query的匹配。重点讨论了Router、Routeconf、RouteRegexp等关键结构以及matcher接口的工作原理。同时,文中通过示例展示了mux的Method匹配和Path匹配功能,并解释了ListenAndServe服务启动的过程。通过对mux源码的研究,有助于理解Go语言HTTP路由的实现。
摘要由CSDN通过智能技术生成

mux源码分析

 mux 是go实现的轻量的路由,可以基于host,path,query匹配

r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  • Router类型结构

 实现了http.handler接口,定义了根路由,可以通过HandleFunc注册多个path 和handler,还有找到匹配项之后调用的中间片

type Router struct {
   
	// Configurable Handler to be used when no route matches.
	NotFoundHandler http.Handler
	// Configurable Handler to be used when the request method does not match the route.
	MethodNotAllowedHandler http.Handler
	// Routes to be matched, in order.
	routes []*Route
	// Routes by name for URL building.
	namedRoutes map[string]*Route
	// If true, do not clear the request context after handling the request.
	//
	// Deprecated: No effect, since the context is stored on the request itself.
	KeepContext bool
	// Slice of middlewares to be called after a match is found
	middlewares []middleware
	// configuration shared with `Route`
	routeConf
}

  • Routeconf类型结构

 Routeconf是“路由器”和“路由”之间共享的公共路由配置,内部结构中 [ ]matcher 用于存储多个匹配条件

 routeRegexpGroup 用于保存匹配成功后提取的参数的实际值。http请求匹配成功后,需要将参数传递到handler处理器中,参数可以从此结构获取

type routeConf struct {
   
	// If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
	useEncodedPath bool

	// If true, when the path pattern is "/path/", accessing "/path" will
	// redirect to the former and vice versa.
	strictSlash bool

	// If true, when the path pattern is "/path//to", accessing "/path//to"
	// will not redirect
	skipClean bool

	// Manager for the variables from host and path.
	regexp routeRegexpGroup

	// List of matchers.
	matchers []matcher

	// The scheme used when building URLs.
	buildScheme string

	buildVarsFunc BuildVarsFunc
}
  • routeRegexp 类型结构
type routeRegexp struct {
   
    // The unmodified template.
    template string
    // The type of match
    regexpType regexpType
    // Options for matching
    options routeRegexpOptions
    // Expanded regexp.
    regexp *regexp.Regexp
    // Reverse template.
    reverse string
    // Vari
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值