英文:
How to use http.HandleFunc with slugs
问题
我正在进行一个Go项目的工作。当我尝试在http.HandleFunc中使用slug时,我得到一个"404页面未找到错误"。当我去掉slug时,我的路由又可以正常工作。
在main函数中,我有:
http.HandleFunc("/products/feedback/{slug}", AddFeedbackHandler)
它调用了:
var AddFeedbackHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
w.Write([]byte("ChecksOut"))
})
当我将路径替换为:
http.HandleFunc("/products/feedback", AddFeedbackHandler)
它又可以正常工作了。可能是什么原因导致这个问题呢?
英文:
I am working on a Go project. When I try to use slugs with http.HandleFunc I get a "404 page not found error". When I take the slug out my routing works again.
In main I have:
http.HandleFunc("/products/feedback/{slug}", AddFeedbackHandler)
Which calls:
var AddFeedbackHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
w.Write([]byte("ChecksOut"))
})
When I replace the path with:
http.HandleFunc("/products/feedback", AddFeedbackHandler)
It works again. What might be causing this?
答案1
得分: 1
请尝试以下代码:
const feedbackPath = "/products/feedback/" // 注意末尾的斜杠。
func AddFeedbackHandler(w http.ResponseWriter, r *http.Request) {
var slug string
if strings.HasPrefix(r.URL.Path, feedbackPath) {
slug = r.URL.Path[len(feedbackPath):]
}
fmt.Println("the slug is: ", slug)
w.Write([]byte("ChecksOut"))
}
http.HandleFunc(feedbackPath, AddFeedbackHandler)
路径末尾的斜杠对于子树匹配是必需的。你可以在ServeMux文档中阅读有关末尾斜杠使用的详细信息。
英文:
Try the following:
const feedbackPath = "/products/feedback/" // note trailing slash.
func AddFeedbackHandler(w http.ResponseWriter, r *http.Request) {
var slug string
if strings.HasPrefix(r.URL.Path, feedbackPath) {
slug = r.URL.Path[len(feedbackPath):]
}
fmt.Println("the slug is: ", slug)
w.Write([]byte("ChecksOut"))
}
Add the handler with this code:
http.HandleFunc(feedbackPath, AddFeedbackHandler)
The trailing slash on the path is required for a subtree match. You can read the details on the use of the trailing slash in the ServeMux documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论