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