gorilla/mux 请求路由和分发的 Go 框架 gorilla/mux

xuanbao • 2024 次点击    
这是一个分享于 的项目,其中的信息可能已经有所发展或是发生改变。
`gorilla/mux` 实现了一个请求路由和分发的 Go 框架。 mux 名字的意思是 &#34;HTTP request multiplexer&#34;. 和标准包 `http.ServeMux`类似,  `mux.Router`根据已注册路由列表匹配传入请求,并调用与URL或其他条件匹配的路由的处理程序。 主要特性: * It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. * URL hosts, paths and query values can have variables with an optional regular expression. * Registered URLs can be built, or &#34;reversed&#34;, which helps maintaining references to resources. * Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. ## 安装 <pre>go get -u github.com/gorilla/mux</pre> ## 代码示例 <pre>func main() { r := mux.NewRouter() r.HandleFunc(&#34;/&#34;, HomeHandler) r.HandleFunc(&#34;/products&#34;, ProductsHandler) r.HandleFunc(&#34;/articles&#34;, ArticlesHandler) http.Handle(&#34;/&#34;, r) }</pre> 这里我们注册了三个 URL 匹配路由进行处理。路径也可以是变量: <pre>r := mux.NewRouter() r.HandleFunc(&#34;/products/{key}&#34;, ProductHandler) r.HandleFunc(&#34;/articles/{category}/&#34;, ArticlesCategoryHandler) r.HandleFunc(&#34;/articles/{category}/{id:[0-9]+}&#34;, ArticleHandler)</pre> 这些名称用于创建路由变量的映射,可以通过调用mux.Vars 获取: <pre>func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) w.WriteHeader(http.StatusOK) fmt.Fprintf(w, &#34;Category: %v\n&#34;, vars[&#34;category&#34;]) } </pre>
授权协议:
BSD
开发语言:
Google Go 查看源码»
操作系统:
跨平台
2024 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传