HttpRouter是一个轻量级但却非常高效的multiplexer。手册:
https://godoc.org/github.com/julienschmidt/httprouter
https://github.com/julienschmidt/httprouter

用法示例

package mainimport ("fmt""github.com/julienschmidt/httprouter""net/http""log"
)func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {fmt.Fprint(w, "Welcome!\n")
}func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}func main() {router := httprouter.New()router.GET("/", Index)router.GET("/hello/:name", Hello)log.Fatal(http.ListenAndServe(":8080", router))
}

首先执行:

go get github.com/julienschmidt/httprouter

然后再启动web服务:

go run xxx.go

和http包的ServeMux用法其实很类似。上面定义了两个httprouter中的handle,类似于http包中的http.HandlerFunc类型,具体的对应关系后文会解释,只要认为它是handler,是处理对应请求的就行了。然后使用New()方法创建了实例,并使用GET()方法为两个模式注册了对应的handler。

需要注意的是,第二个模式"/hello/:name",它可以用来做命名匹配,类似于正则表达式的命名捕获分组。后面会详细解释用法。

httprouter用法说明

Variables
func CleanPath(p string) string
type Handle
type Param
type Paramsfunc ParamsFromContext(ctx context.Context) Paramsfunc (ps Params) ByName(name string) string
type Routerfunc New() *Routerfunc (r *Router) DELETE(path string, handle Handle)func (r *Router) GET(path string, handle Handle)func (r *Router) HEAD(path string, handle Handle)func (r *Router) Handle(method, path string, handle Handle)func (r *Router) Handler(method, path string, handler http.Handler)func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)func (r *Router) Lookup(method, path string) (Handle, Params, bool)func (r *Router) OPTIONS(path string, handle Handle)func (r *Router) PATCH(path string, handle Handle)func (r *Router) POST(path string, handle Handle)func (r *Router) PUT(path string, handle Handle)func (r *Router) ServeFiles(path string, root http.FileSystem)func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

type Handle

httprouter中的Handle类似于http.HandlerFunc,只不过它支持第三个参数Params。

type Handle func(http.ResponseWriter, *http.Request, Params)Handle is a function that can be registered to a route to handle HTTPrequests. Like http.HandlerFunc, but has a third parameter for the values ofwildcards (variables).

例如前面示例中的Index()和Hello()都是Handle类型的实例。

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {fmt.Fprint(w, "Welcome!\n")
}func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

注册handler

httprouter.Router类型类似于http包中的ServeMux,它实现了http.Handler接口,所以它是一个http.Handler。它可以将请求分配给注册好的handler。

type Router struct {}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

除此之外,Router提供了不少方法,用来指示如何为路径注册handler。

func (r *Router) Handle(method, path string, handle Handle)
func (r *Router) Handler(method, path string, handler http.Handler)
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

httprouter.Handle()用于为路径注册指定的Handle,而httprouter.Handle对应于http.HandlerFunc,所以是直接将Handle类型的函数绑定到指定路径上。同时,它还可以指定http方法:GET, POST, HEAD, PUT, PATCH, DELETE, OPTIONS。

这些方法还有对应的各自缩写:

func (r *Router) DELETE(path string, handle Handle)
func (r *Router) GET(path string, handle Handle)
func (r *Router) HEAD(path string, handle Handle)
func (r *Router) OPTIONS(path string, handle Handle)
func (r *Router) PATCH(path string, handle Handle)
func (r *Router) POST(path string, handle Handle)
func (r *Router) PUT(path string, handle Handle)

例如,Get()等价于route.Handle("GET", path, handle)。

例如上面的示例中,为两个路径注册了各自的httprouter.Handle函数。

router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)

Handler()方法是直接为指定http方法和路径注册http.Handler;HandlerFunc()方法则是直接为指定http方法和路径注册http.HandlerFunc。

Param相关

type Param struct {Key   stringValue string
}
Param is a single URL parameter, consisting of a key and a value.type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.func (ps Params) ByName(name string) string
ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

Param类型是key/value型的结构,每个分组捕获到的值都会保存为此类型。正如前面的示例中:

router.GET("/hello/:name", Hello)

这里的:name就是key,当请求的URL路径为/hello/abc,则key对应的value为abc。也就是说保存了一个Param实例:

Param{Key: "name",Value: "abc",
}

更多的匹配用法稍后解释。

Params是Param的slice。也就是说,每个分组捕获到的key/value都存放在这个slice中。

ByName(str)方法可以根据Param的Key检索已经保存在slice中的Param的Value。正如示例中:

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}router.GET("/hello/:name", Hello)

这里ByName("name")将检索保存在slice中,Key="name"的Param,且返回这个Param中的Value。

由于Params是slice结构,除了ByName()方法可以检索key/value,通过slice的方法也可以直接检索:

ps[0].Key
ps[0].Value

路径匹配规则

httprouter要为路径注册handler的适合,路径可以进行命名捕获。有两种命名捕获的方式:

Syntax    Type
:name     named parameter
*name     catch-all parameter

其中:name的捕获方式是匹配内容直到下一个斜线或者路径的结尾。例如要为如下路径注册handler:

Path: /blog/:category/:post

当请求路径为:

/blog/go/request-routers            match: category="go", post="request-routers"
/blog/go/request-routers/           no match, but the router would redirect
/blog/go/                           no match
/blog/go/request-routers/comments   no match

*name的捕获方式是从指定位置开始(包含前缀"/")匹配到结尾:

Path: /files/*filepath/files/                             match: filepath="/"
/files/LICENSE                      match: filepath="/LICENSE"
/files/templates/article.html       match: filepath="/templates/article.html"
/files                              no match, but the router would redirect

再解释下什么时候会进行重定向。在Router类型中,第一个字段控制尾随斜线的重定向操作:

type Router struct {RedirectTrailingSlash bool...
}

如果请求的URL路径包含或者不包含尾随斜线时,但在注册的路径上包含了或没有包含"/"的目标上定义了handler,但是会进行301重定向。简单地说,不管URL是否带尾随斜线,只要注册路径不存在,但在去掉尾随斜线或加上尾随斜线的路径上定义了handler,就会自动重定向。

例如注册路径为/foo,请求路径为/foo/,会重定向。

下面还有几种会重定向的情况:

注册路径:/blog/:category/:post
请求URL路径:/blog/go/request-routers/注册路径:/blog/:category
请求URL路径:/blog/go注册路径:/files/*filepath
请求URL路径:/files

Lookup()

func (r *Router) Lookup(method, path string) (Handle, Params, bool)

Lookup根据method+path检索对应的Handle,以及Params,并可以通过第三个返回值判断是否会进行重定向。

转载于:https://www.cnblogs.com/f-ck-need-u/p/10020917.html

Go Web:HttpRouter路由相关推荐

  1. Go Web——HttpRouter路由

    文章目录 简介 一 快速入门 二 参数 2.1 命名参数 2.2 Catch-All参数 三 HttpRouter 请求方法 四 基于 HttpRouter 的 Web 框架(了解) 简介 HttpR ...

  2. ASP.NET Web API 路由对象介绍

    前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了一些微小的修改,这也是根据每个框架的特性来制定 ...

  3. Go Web:HttpRouter路由(一)

    2019独角兽企业重金招聘Python工程师标准>>> HttpRouter是一个轻量级但却非常高效的multiplexer. 手册: https://godoc.org/githu ...

  4. Web API路由和动作选择

    前言 本文描述ASP.NET Web API如何把一个HTTP请求路由到控制器的一个特定的Action上.关于路由的总体概述可以参见上一篇教程 http://www.cnblogs.com/aehyo ...

  5. ASP.NET Web API路由规则(二)

    默认的规则 在ASP.NET MVC4中 global.asax.cs代码中并无注册默认路由规则的代码 代码如下: public class WebApiApplication : System.We ...

  6. Asp.net Web Api 路由 和 异常处理

    一.路由: 新建一个ASP.NET MVC4 Web Application项目之后,我们会发现在网站根目录下有个App_Start文件夹.找到下面的RouteConfig.cs文件,如下: publ ...

  7. Vert.x(vertx) Web开发-路由

    在Vert.x 创建HTTP服务 中我们已经创建了一个简单的HttpServer,但这个HttpServer比较低级,对于请求参数解析.Session等常用功能都需要我们通过编码实现,也就是要重复造轮 ...

  8. Web开发中的路由是什么意思?(关键词:Web开发/路由)

    路由就是URL到函数的映射. 在web开发中,"route"是指根据url, 分配到对应的处理程序. 路由: 就是一个路径的解析,根据客户端提交的路径,将请求解析到相应的控制器上: ...

  9. webapi 路由限制命名控件_解决Web API路由配置支持Area及命名空间参数

    usingSystem;usingSystem.Collections.Concurrent;usingSystem.Collections.Generic;usingSystem.Linq;usin ...

最新文章

  1. hitchhiker部署_Hitchhiker的React Router v4指南:无限远的递归路径!
  2. sap 客户信贷配置与管理解析
  3. Vue 中的 v-if 和 v-show 修饰符
  4. linux 禁ping设置
  5. (转)基于libRTMP的流媒体直播之 AAC、H264 推送
  6. 局域网远程维护工具DAMEWARE NT 需要开通IPC和ADMIN通道
  7. pyqt5菜鸟教程_PyQt5教程(一)——第一个PyQt5程序
  8. 视频教程-大学数学实验(MATLAB版)-其他
  9. 做正确的事(效果)比正确的做事(效率)更重要
  10. 如何卸载CAD 2019 ?怎么把AutoCAD 2019彻底卸载删除干净重新安装的方法【转载】
  11. MySQL - 大量 sending data 状态进程,让数据库性能急剧下降。
  12. python获取元素在数组中的位置
  13. 文华软件登录显示请选择服务器,文华随身行 请先登入云服务器
  14. 外国用户和国内用户看待浏览器的问题
  15. 【html标签复习】
  16. FreeNAS 简介
  17. 使用TensorFlow识别交通标志
  18. Android layout_gravity 和 gravity的区别
  19. Cron表达式的语法及详细用法
  20. 胎心仪/指夹式血氧仪/监护仪/数码管电量显示/数字闹钟等,低功耗抗干扰LED数码管显示(数显)驱动IC-VK1S68C SSOP24小体积封装,可驱动70/66/52/60点阵

热门文章

  1. 【CCF】201709-1打酱油
  2. ext2.0 主体皮肤 (xtheme-black)
  3. C#报表控件ReportViewer rdlc 例(1) .
  4. ReportViewer教程(8)-对报表作一些调整(格式和属性)
  5. 漫步数学分析十二——嵌套
  6. 【C++】C++类的学习(三)——运算符重载与友元函数
  7. Python读取文本文档转化成列表
  8. 随机样本一致性:一种用于图像分析和自动制图的模型拟合模型(3)--(P3P的迭代解)
  9. 转换预定义的字符为html实体,php把一些预定义的 HTML 实体转换为字符。
  10. 方法重载与重写,返回类型