gpt4 book ai didi

go - net/http 呈现根路由,即使我转到不存在的路由

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:26 25 4
gpt4 key购买 nike

我有这些路线:

  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
renderAndExecuteTemplate(w, r, "page/index.tmpl", nil)
})

http.HandleFunc("/route1", func(w http.ResponseWriter, r *http.Request) {
renderAndExecuteTemplate(w, r, "page/route1.tmpl", nil)
})


http.HandleFunc("/route2", func(w http.ResponseWriter, r *http.Request) {
renderAndExecuteTemplate(w, r, "page/route2.tmpl", nil)
})

有效。

但是,当我转到不存在的路由时:“localhost/fdsafdsafdsfds”,它仍然呈现“索引”页面。

为什么?如何预防呢?

最佳答案

来自docs :

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

防止这种情况的一种方法是构建一个查看请求的处理程序:

http.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}

renderAndExecuteTemplate(w, r, "page/index.tmpl", nil)
})

关于go - net/http 呈现根路由,即使我转到不存在的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53822760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com