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


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
}
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM