分享
Golang自带的http包的路由规则问题
cythical-l-zc · · 2262 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
1、调用下面的方法开启一个http监听服务
http.HandleFunc("/hello/", helloHandler)
err := http.ListenAndServe(":8080", nil)
if err= nil {
log.Fatal("ListenAndServe: ", err.Error())
}
2、路由规则中新增了"/hello"和"/hello/"两个key对应的handler(helloHandler)
3、跟踪http\server.go源码查看到路由匹配规则中,通过高亮的代码可以让我们分析出来,
假如我们请求路由"/hello/beijing",那么"/hello/"会被匹配到,但是这个通常不是我们想要的,
如果使用原生的http包路由规则为了避免这种情况,在注册路由的时候不要以"/"结尾,即注册"/hello"而不是"/hello/"
func pathMatch(pattern, path string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == path
}
return len(path) >= n && path[0:n] == pattern
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信2262 次点击
上一篇:技术:超级实用的电脑小技巧
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
1、调用下面的方法开启一个http监听服务
http.HandleFunc("/hello/", helloHandler)
err := http.ListenAndServe(":8080", nil)
if err= nil {
log.Fatal("ListenAndServe: ", err.Error())
}
2、路由规则中新增了"/hello"和"/hello/"两个key对应的handler(helloHandler)
3、跟踪http\server.go源码查看到路由匹配规则中,通过高亮的代码可以让我们分析出来,
假如我们请求路由"/hello/beijing",那么"/hello/"会被匹配到,但是这个通常不是我们想要的,
如果使用原生的http包路由规则为了避免这种情况,在注册路由的时候不要以"/"结尾,即注册"/hello"而不是"/hello/"
func pathMatch(pattern, path string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == path
}
return len(path) >= n && path[0:n] == pattern
}