gorilla/mux 实现了一个请求路由和分发的Go框架。
mux名字的意思是"HTTPrequestmultiplexer".和标准包 http.ServeMux类似, mux.Router根据已注册路由列表匹配传入请求,并调用与URL或其他条件匹配的路由的处理程序。
主要特性:
Itimplementsthe http.Handler interfacesoitiscompatiblewiththestandard http.ServeMux.RequestscanbematchedbasedonURLhost,path,pathprefix,schemes,headerandqueryvalues,HTTPmethodsorusingcustommatchers.URLhosts,pathsandqueryvaluescanhavevariableswithanoptionalregularexpression.RegisteredURLscanbebuilt,or"reversed",whichhelpsmaintainingreferencestoresources.Routescanbeusedassubrouters:nestedroutesareonlytestediftheparentroutematches.Thisisusefultodefinegroupsofroutesthatsharecommonconditionslikeahost,apathprefixorotherrepeatedattributes.Asabonus,thisoptimizesrequestmatching.安装goget-ugithub.com/gorilla/mux代码示例funcmain(){r:=mux.NewRouter()r.HandleFunc("/",HomeHandler)r.HandleFunc("/products",ProductsHandler)r.HandleFunc("/articles",ArticlesHandler)http.Handle("/",r)}这里我们注册了三个URL匹配路由进行处理。路径也可以是变量:
r:=mux.NewRouter()r.HandleFunc("/products/{key}",ProductHandler)r.HandleFunc("/articles/{category}/",ArticlesCategoryHandler)r.HandleFunc("/articles/{category}/{id:[0-9]+}",ArticleHandler)这些名称用于创建路由变量的映射,可以通过调用mux.Vars获取:
funcArticlesCategoryHandler(whttp.ResponseWriter,r*http.Request){vars:=mux.Vars(r)w.WriteHeader(http.StatusOK)fmt.Fprintf(w,"Category:%v\n",vars["category"])}
评论