英文:
Go web server does not process /delete/ pattern correctly
问题
我刚刚尝试了一个谷歌GO官方示例编写Web应用程序,我试图添加一个删除页面的功能,但没有成功。原因是,如果将"/delete/"
作为参数传递给http.HandleFunc()
函数,你将始终得到404页面未找到的错误。任何其他的"foobar"
字符串都能正常工作。
简化的代码:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", r.URL.Path)
}
func main() {
http.HandleFunc("/hello/", handler)
//http.HandleFunc("/delete/", handler)
http.ListenAndServe(":8080", nil)
}
重现步骤:
- 编译并从浏览器中调用
http://localhost:8080/hello/world
- 输出为
/hello/world
- 现在将
http.HandleFunc("/hello/", handler)
注释掉,并取消注释http.HandleFunc("/delete/", handler)
- 编译并从浏览器中调用
http://localhost:8080/delete/world
- 结果为
404页面未找到
,预期为/delete/world
问题:
"/delete/"
模式有特殊含义吗?这是有技术原因还是只是一个错误?
英文:
I just played with a google GO official example Writing Web Applications I tried to add a functionality to delete pages and it has not worked. The reason is that if you pass "/delete/"
as a parameter to http.HandleFunc()
function you get always 404 Page not found. Any other "foobar"
string works as expected.
Simplified code:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", r.URL.Path)
}
func main() {
http.HandleFunc("/hello/", handler)
//http.HandleFunc("/delete/", handler)
http.ListenAndServe(":8080", nil)
}
Steps to reproduce:
- Compile and call
http://localhost:8080/hello/world
from a browser - Output is
/hello/world
- Now comment
http.HandleFunc("/hello/", handler)
and uncommenthttp.HandleFunc("/delete/", handler)
- Compile and call
http://localhost:8080/delete/world
from a browser - Result is
404 page not found
, expected/delete/world
Question:
Is there any special meaning for "/delete/"
pattern? Is there any technical reason for that or is it just a bug?
答案1
得分: 2
这在这里运行得很好,不可能在一个情况下工作而在另一个情况下不工作。你只是在两行代码之间将字符串"hello"
更改为字符串"delete"
。
我建议你再仔细尝试一次。问题肯定出在其他地方。
真正的原因是没有检查ListenAndServe
的错误结果。一个旧的副本在后台运行,并且缺乏错误处理使其不被察觉。浏览器从一个旧的服务器获取结果。
英文:
This works fine here, and it cannot possibly work in one situation and not the other. You're just changing the string "hello"
for the string "delete"
between the two lines.
I suggest trying again more carefully. It must be a detail elsewhere.
The real reason was not checking the error result of ListenAndServe
. An old copy was running in background, and the lack of error handling made it go unperceived. The browser was getting results from an old server.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论