初探httprouter
httprouter
是一个高性能、可扩展的HTTP路由,可以作为golang默认路由net/http的替代。
关键词:httprouter
安装
1 | go get -u "github.com/julienschmidt/httprouter" |
一个例子作为开始
1 | package main |
上面的代码中,HelloWorld是一个handle httprouter.Handle类型,需要传入三个参数,三个参数的作用以后说。该handle在main函数忠被注册到/hi路径上。运行代码会得到一下效果。

HTTP Method
1 | func (r *Router) GET(path string, handle Handle) { |
路由匹配
net/http的路由匹配
1 | // /api,可以访问到 |
httprouter的路由匹配
两者路由命名捕获方式:(是路由命名不是路由参数)
:name的捕获方式是匹配内容直到下一个斜线或者路径的结尾1
2
3
4
5
6
7
8Path: /blog/:category/:post
router.GET("/blog/:category/:post", Hello) //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的方式是从指定位置开始(包含前缀"/")匹配到结尾1
2
3
4
5
6
7
8Path: /files/*filepath
router.GET("/files/*filepath", Hello) //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
获取路由命名的参数
1 | func HelloWorld(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { |
httprouter重定向
如果请求的URL路径包含或者不包含尾随斜线时,但在注册的路径上包含了或没有包含"/"的目标上定义了handler,但是会进行301重定向。简单地说,不管URL是否带尾随斜线,只要注册路径不存在,但在去掉尾随斜线或加上尾随斜线的路径上定义了handler,就会自动重定向。
1 | func New() *Router { |
下面有几种会重定向的情况
1 | 注册路径:/blog/:category/:post |
httprouter lookup
Lookup根据method+path检索对应的Handle,以及Params,并可以通过第三个返回值判断是否会进行重定向。
1 | func (r *Router) Lookup(method, path string) (Handle, Params, bool) |
httprouter获取请求相关的信息
1 | func HelloWorld(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { |
其中PostForm获取x-www-form-urlencoded发送的表单,Form获取明文发送如http://127.0.0.1/hi/xxx?user=xxx如user=xxx的信息。
http返回信息
1 | func HelloWorld(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { |
第一行返回http请求状态码
第二行返回Body,通常是返回一个json
第三行是返回Header,格式是map