课上讲义httprouter源码分析_第1页
课上讲义httprouter源码分析_第2页
课上讲义httprouter源码分析_第3页
课上讲义httprouter源码分析_第4页
课上讲义httprouter源码分析_第5页
已阅读5页,还剩8页未读, 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

typeRouter{trees//Enablesautomaticredirectionifthecurrentroutecan'tbematchedbut//handlerforthepathwith(without)thetrailingsash//Forexampleif/foo/isrequestedbutaroueonlyexistsfor/foo, isredirectedto/foowithhttpstatuscode301forGET//and307forallotherrequestmethodsRedirectTrailingSlashbool//Ifenabled,theroutertriestofixthecurrentrequestpath,if//handleisregisteredfor//Firstsuperfluouspatheleentsike../or//are//Afterwardstherouterdoesacse-insensitivelookupofthecleaned//Ifahandlecanbefoundforthisroute,theroutermakesa//tothecorrectedatwithstatuscode301forGETrequestsand307//allotherrequest//Forexample/FOOand/..//Foocouldberedirectedto//RedirectTrailingSlashisindependentofthisoption.RedirectFixedPathbool//Ifenabled,therouterchecksifanothermethodisallowedfor//currentroute,ifthecurrentrequestcannotbe//Ifthisisthecase,therequestisansweredwith'MethodNot//andHTTPstatuscode//IfnootherMethodisallowed,therequestisdelegatedtothe//handler.HandleMethodNotAllowedbool//Ifenabled,therouterautomaticallyrepliestoOPTIONS//CustomOPTIONShandlerstakepriorityoverautomaticreplies.HandleOPTIONSbool//Anoptionalhttp.HandlerthatiscalledonautomaticOPTIONS//ThehandlerisonlycalledifHandleOPTIONSistrueandno//handlerforthespecificpathwas//The"Allowed"headerissetbeforecallingthehandler.GlobalOPTIONShttp.Handler//Cachedvalueofglobal(*)allowedmethodsglobalAllowedstring//Configurablehttp.Handlerwhichiscalledwhennomatchingroute//found.Ifitisnotset,http.NotFoundisused.NotFoundhttp.Handler//Configurablehttp.Handlerwhichiscalledwhena//cannotberoutedandHandleMethodNotAllowedis//Ifitisnotset,http.Errorwithhttp.StatusMethodNotAllowedis//The"Allow"headerwithallowedrequestmethodsissetbeforethe//iscalled.MethodNotAllowedhttp.Handler//Functiontohandlepanicsrecoveredfromhttphand//Itshouldbeusedtogenerateaerrorpageanreurnthehttperror//500(InternalServer//Thehandlercanbeusedtokeepyourserverfromcrashingbecause//unrecoveredPanicHandlerfunc(http.ResponseWriter,*http.Request,}treesmap[string]*node它是一个关键。其中,node定义如下:typetypenode{path wildChildbool maxParamsuint8priorityuint32 children[]*node }routerrouter:=router.GET("/search/",func1)router.GET("/support/",func2)router.GET("/blog/:post/",func3)router.GET("/about-us/",func4)router.GET("/about-us/team/",func5)router.GET("/contact/",9\32121 1 21 1其中。与//addRouteaddsanodewiththegivenhandletothe//Notconcurrency-func(n*node)addRoute(pathstring,handle{fullPath:=pathnumParams:=//non-emptyiflen(n.path)>0||len(n.children)>{walk:for//UpdatemaxParamsofthecurrentnodeifnumParams>n.maxParams{n.maxParams=}//Findthelongestcommon//Thisalsoimpliesthatthecommonprefixcontainsno':'or//sincetheexistingkeycan'tcontainthosechars.i:=0max:=min(len(path),len(n.path))fori<max&&path[i]==npth[i]{}//Splitifi<{child:= wildChild:n.wildChild, static,indices:children:n.children, priority:n.priority-1,}//UpdatemaxParams(maxofallchildren)fori:=rangechild.children{ifchild.children[i].maxParams>{child.maxParams=}}n.children=//[]byteforproperunicodecharconversion,seen.indices=string([]byte{n.path[i]})n.path=path[:i]n.handle=niln.wildChild=false}//Makenewnodeachildofthisnodeifi<len(path){path=ifn.wildChildn=n.children[0]//UpdatemaxParamsofthechildnodeifnumParams>n.maxParams{n.maxParams=}//Checkifthewildcardiflen(path)>=len(n.path)&&npath==path[:len(n.path)]//AddingachildtoacatchAlisnotposiblen.nType!=catchAll&&//Checkforlongerwildcard,e.g.:nameand:names(len(n.path)>=len(path)||pat[len(n.path)]=='/'){continue}else//varpathSegifn.nType=={pathSeg=}elsepathSeg=strings.SplitN(path,"/",}prefix:=fullPath[:strings.Index(fullPath,pathSeg)]+n.pathpanic("'"+pathSeg+"'innewpath'"+fullPath swithexistingwildcard'"+n.path+"'inexistingprefix'"+prefix+}}c:=//slashafterifn.nType==param&&c=='/'&&len(n.children)=={n=continuewalk}//Checkifachildwiththenextpathbyteexistsfori:=0;i<len(n.indices);i++{ifc==n.indices[i]i=n.incrementChildPrio(i)n=n.children[i]continue}}//Otherwiseinsertifc!=':'&&c!='*'//[]byteforproperunicodecharconversion,see#65n.indices+=string([]byte{c})child&node{maxParams:}n.children=append(n.children,child)n.incrementChildPrio(len(n.indices-1)n=child}n.insertChild(numParams,pth,fullPath,handle)}elseifi==len(path) //Mkenodea(in-path)leafifn.handle!=il{panic("ahandleisalreadyregisteredforpath'"+fullPath+}n.handle=}}}else{//Emptyn.insertChild(numParams,path,fullPath,handle)n.nType=root}}funcfunc(n*node)insertChild(numParamsuint8,path,fullPathstring,handleHandle){varoffsetint//alreadyhandledbytesofthe//findprefixuntilfirstwildcard(beginningwith':''orfori,max:=0,len(path);numParams>0;i++c:=ifc!=':'&&c!={}//findwildcardend(either'/'orpathend)end:=i+1forend<max&&path[end]!={switchpath[end]//thewildcardnamemustnotcontain':'and'*'case':','*':panic("onlyonewildcardperpathsegmentisallowed,has:'"+path[i:]+"'inpath'"+fullPath+"'")}}//checkifthisNodeexistingchildrenwhichwould//unreachableifweinsertthewildcardhereiflen(n.children)>0{panic("wildcardroute'"+path[i:end]"'swithexistingchildreninpath'+fullPath+}//checkifthewildcardhasanameifend-i<2{panic("wildcardsmustbeamedithanon-emptynameinpath'"+fullPath+"'")}ifc==':'{////splitpathatthbeginningofthewildcardifi>0{n.path=path[offset:i]offset=i}child:=&node{nType:maxParams:numParams,}n.children=[]*node{child}n.wildChild=truen=child//ifthepathdoesn'tendwiththewildcard,then//willbeanothernon-wildcardsubpathstartingwith'/'ifend<max{n.path=path[offset:end]offset=endchild&node{maxParams:numParams,priority:1,}n.children=[]*node{child}n=child}}else{//ifend!=max||numParams>1panic("catch-allroutesareonlyallowedattheendofthepathinpath'"+fullPath+"'")}iflen(n.path)>0&&n.path[len(n.path)-1]=/ swithexistinghndlforthepathsegmentrootinpath'"+fullPath+"'")}//currentlyfixedwidth1for'/ifpath[i]!='/'panic("no/beforecatc-allnpath'"+fullPath+}n.path=path[ofset//firstnode:catchAllnodewithemptypathchild:=&node{wildChild:true, maxParams:1,}//updatemaxParamsoftheparentnodeifn.maxParams<1{n.maxParams=}n.children=[]*node{child}n.indices=string(path[i])n=child//secondnode:nodeholdingthevariablechild=&node{maxParams:1, priority:1,}n.children=}}//insertremainingpathpartandhandletotheleafn.path=path[offset:]n.handle=}//Returnsthehandleregisteredwiththegivenpath(key).Thevalues//wildcardsaresavedtoa//Ifnohandlecanbefound,aTSR(trailingslash mendation//madeifahandleexistswithanextra(wihoutthe)trailingslashfor//givenfunc(n*node)getValue(pathsting)handleHandle,pParams,tsr{walk://outerloopforwalkingthtreefor{iflen(path)>lnn.path)ifpath[:len(n.pah)]=={path=path[len(n//Ifthisnodedoesnothaveawildcard(paramor//child,wecanjustlookupthenextchildnodeand//towalkdownthetreeif!n.wildChild{c:=fori:=0;i<len(n.indices);{ifc==n.indices[i]{n=n.children[i]continuewalk}}//Nothing//We mendtoredirecttothesameURLwithout//trailingslashifaleafexistsforthatpath.tsr=(path=="/"&&n.handle!=nil)}//handlewildcardchildn=n.children[0]switchn.nType{case//findparamend(either'/'orpathend)end:=0forend<len(path)&&path[end]!={}//saveparamvalueifp==nil{//lazyp=make(Params,0,}i:=p=p[:i+1]//expandslicewithinprealocaedcapacityp[i].Key=n.path[1:]p[i].Value=//weneedtogodeeper!ifend<len(path){iflen(n.children)>{path=path[end:]n=n.children[0]continuewalk}//...butwetsr=(len(path)==end+1)}ifhandle=n.handle;handle!={}elseiflen(n.children)==1//Nohandlefound.Checkifahandleforthispath+//trailingslashexistsforTSR n=n.children[

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论