如果我在端口8080上运行以下简单的http服务器代码,一切都按预期工作。如果我在端口80上运行相同的代码,只需更改端口,处理函数会在每个请求中执行两次。为什么,以及如何解决它?http.ListenAndServe处理函数在端口80上执行两次
// httptest project main.go
package main
import (
"net/http"
"log"
"fmt"
"html"
)
var count int
func defaultHandler(w http.ResponseWriter, r *http.Request) {
count++
fmt.Fprintf(w, "Hello, %q count=%d", html.EscapeString(r.URL.Path), count)
fmt.Println(count,r.RemoteAddr)
}
func main() {
http.HandleFunc("/", defaultHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
如果我输入localhost:8080在浏览器中,我得到从1开始以计数的响应,并与每个新的请求增加1。
如果我将代码更改为端口80,并在浏览器中输入localhost或localhost:80,则会得到第一个响应,计数从1开始,但随后每增加2个请求。与此同时,控制台输出的打印语句被执行两次。 3个请求在端口80上运行时
终端控制台:
>go run main.go
1 [::1]:51335
2 [::1]:51335
3 [::1]:51335
4 [::1]:51335
5 [::1]:51335
6 [::1]:51335
在浏览器中的反应是Hello, "/" count=1
,Hello, "/" count=3
和Hello, "/" count=5
。
我一直在使用Go版本go1.9.2 windows/amd64和最新的Google Chrome浏览器在Windows 10上本地运行此程序。
但是,我在远程Linux服务器上的一个简单Web应用程序中检测到问题,其中的代码已使用go版本go1.9.1 linux/amd64进行编译。
通过添加'if r.URL.Path!=“/”{http.Error(w,“Not Found”,404);返回}'到处理程序的开始。 –