英文:
How do I http.ListenAndServe "/" and not have it respond to every path?
问题
在一个小的Golang服务器中,我有以下的代码:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
基本上允许你在服务器的根目录上访问而不会发生任何可怕的事情。
问题是你也可以访问/foo/bar/blah...
,而且它仍然有效。这不是我想要的。
我该如何明确限制只能访问我指定的路径?
英文:
I have the following code in a small golang server:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
Basically allowing you to hit the root of the server without anything scary happening.
The issue is that you can also hit /foo/bar/blah...
and it still works. Which I don't want.
How can I explicitly restrict it to what I say?
答案1
得分: 4
请将以下代码添加到您的处理程序的开头:
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
这段代码的作用是检查请求的URL路径是否为根路径("/"),如果不是,则返回404错误页面。
英文:
Add the following code to the beginning of your handler:
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论