Go web服务器无法正确处理/delete/模式。

huangapple go评论144阅读模式
英文:

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)
}

重现步骤:

  1. 编译并从浏览器中调用http://localhost:8080/hello/world
  2. 输出为/hello/world
  3. 现在将http.HandleFunc("/hello/", handler)注释掉,并取消注释http.HandleFunc("/delete/", handler)
  4. 编译并从浏览器中调用http://localhost:8080/delete/world
  5. 结果为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:

  1. Compile and call http://localhost:8080/hello/world from a browser
  2. Output is /hello/world
  3. Now comment http.HandleFunc("/hello/", handler) and uncomment http.HandleFunc("/delete/", handler)
  4. Compile and call http://localhost:8080/delete/world from a browser
  5. 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.

huangapple
  • 本文由 发表于 2013年9月4日 05:14:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/18601629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定