gorilla/mux 实现了一个请求路由和分发的Go框架。
mux名字的意思是"HTTPrequestmultiplexer".和标准包 http.ServeMux类似, mux.Router根据已注册路由列表匹配传入请求,并调用与URL或其他条件匹配的路由的处理程序。
主要特性:
Itimplemetsthe http.Hadler iterfacesoitiscompatiblewiththestadard http.ServeMux.RequestscabematchedbasedoURLhost,path,pathprefix,schemes,headeradqueryvalues,HTTPmethodsorusigcustommatchers.URLhosts,pathsadqueryvaluescahavevariableswithaoptioalregularexpressio.RegisteredURLscabebuilt,or"reversed",whichhelpsmaitaiigreferecestoresources.Routescabeusedassubrouters:estedroutesareolytestediftheparetroutematches.Thisisusefultodefiegroupsofroutesthatsharecommocoditioslikeahost,apathprefixorotherrepeatedattributes.Asabous,thisoptimizesrequestmatchig.安装goget-ugithub.com/gorilla/mux代码示例fucmai(){r:=mux.NewRouter()r.HadleFuc("/",HomeHadler)r.HadleFuc("/products",ProductsHadler)r.HadleFuc("/articles",ArticlesHadler)http.Hadle("/",r)}这里我们注册了三个URL匹配路由进行处理。路径也可以是变量:
r:=mux.NewRouter()r.HadleFuc("/products/{key}",ProductHadler)r.HadleFuc("/articles/{category}/",ArticlesCategoryHadler)r.HadleFuc("/articles/{category}/{id:[0-9]+}",ArticleHadler)这些名称用于创建路由变量的映射,可以通过调用mux.Vars获取:
fucArticlesCategoryHadler(whttp.ResposeWriter,r*http.Request){vars:=mux.Vars(r)w.WriteHeader(http.StatusOK)fmt.Fpritf(w,"Category:%v\",vars["category"])}
评论