开始做笔记…(之前面试被怼了)
路由匹配原理(Regexp in Router)
First, let’s go through its *** usage ***:
Let’s cut it into two parts:
HandlerFunc(path,handler)
then let’s see *** Route.Path(path) *** :
In *** r.err = r.addRegexpMatcher(tpl, regexpTypePath) ***the *** regexpTypePath=0 *** means this is for matching Path instead of Host/Port/Prefix/Query
Continue, Go into method *** addRegexpMatcher() ***:
We will find that we only enter the first *** if *** block (from line 4 - line 11):Getinto the *** newRouteRegexp() ***
I will roughly split the above code into serveral parts as below:
Procedure :
- 根据括号筛选变量 (braceIndices)It will check the all *** {variable} *** in Path and save them into a slice:
====>
- 移除斜杠 (Remove endSlash)
====>
- traverse idxs(variables)
返回后回到 *func (r Route) addRegexpMatcher(tpl string, typ regexpType) error func,这个函数最后会把match加入matchers里面
Vars()
The place used by mux to save variables called *** context *** (上下文)And we have to talk about the *** context in ‘net/http’ ***:
Then go into *** contextGet(r,varsKey) ***:
Context struct in *** “net/http” ***可以参考自己写的一个context
一切到最后,handleFunc()会调用ServeHTTP(w,req),里面就会把RouteMatch的vars导出,放入http包里的context里