Go 1.22 新ServeMux的Proposal
go在1.22中为开发者带来了新的ServeMux
,可以支持更丰富的路由表达式,详细用法见 https://go.dev/blog/routing-enhancements。 在使用中我发现想要获取当前路由匹配的信息在Request
中是无法直接获取的,需要使用func (mux *ServeMux) Handler(r *Request)
再执行一边来拿到当前匹配的Pattern
。不说在很大请求量时频繁调用带来的开销,哪怕小请求量下这样的浪费也是让人于心不忍的。在Gorilla Mux中,router向Request
的Context
设置了routeKey
来达到传递匹配的Route的信息。需要获取这个信息时要从Request
的Context
中找到这个routeKey
,也有不小的开销。
在这样的情况下我起了一个新的Proposal,期望能够暴露出Request
在被ServeMux
处理时原本就匹配到的Pattern
信息,https://github.com/golang/go/issues/66405,这样就避免了额外的调用查询,也能够提供给第三方框架设置这个值。此处增加Pattern
字段之后不管是新版本的ServeMux
还是第三方router,只需要直接向Request
设置这个字段的值即可。字段类型为string
,能够满足传递信息的需求。
对于历史版本,按照Russ Cox大佬的意思,不做修改 https://github.com/golang/go/issues/66405#issuecomment-2101071117
We should leave the old mux behavior unchanged. It is still accessible from a GODEBUG but we want people to move off it. We are not updating it, and eventually it may be removed. Adding new API to it gives the opposite impression.
最终代码变更见 https://github.com/golang/go/pull/66618
这篇文章写得深入浅出,让我这个小白也看懂了!