首页 > Web开发 > 详细

Golang自带的http包的路由规则问题

时间:2017-11-03 18:24:15      阅读:343      评论:0      收藏:0      [点我收藏+]
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
}
 

Golang自带的http包的路由规则问题

原文:http://www.cnblogs.com/cythical-l-zc/p/7779383.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!