Update: The question title can be misleading. This was not Go's fault at all.
See the first comment or the accepted answer.
以下代码(好吧,几乎相同)计算Linux下的页面浏览量,但在Windows下计算它们是双倍的。
有人可以找出原因吗?
package main
import (
"fmt"
"http"
)
func main() {
println("Running")
http.HandleFunc("/", makeHomeHandler())
http.ListenAndServe(":8080", nil)
}
// this version compiles and run OK under the Linux version of Golang
func makeHomeHandler() func(c *http.Conn, r *http.Request) {
views := 1
return func(c *http.Conn, r *http.Request) {
fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)
views++
}
}
/*
// this version compiles and run OK under the mingw version of Golang
// it uses a different argument type for the handler function,
// but the counter says "1 so far", then "3 so far", "5 so far", and so on.
func makeHomeHandler() func(c http.ResponseWriter, r *http.Request) {
views := 1
return func(c http.ResponseWriter, r *http.Request) {
fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)
views++
}
}
*/
明杰:
http://localhost:8080/monkeys => Counting monkeys, 1 so far.
http://localhost:8080/monkeys => Counting monkeys, 3 so far.
http://localhost:8080/donkeys => Counting donkeys, 5 so far.
这可能是个错误吗?
跟进:
事实上,如果我为另一个页面定义一个额外的处理程序,例如:
http.HandleFunc("/test", testPageHandler)
Wich没有闭包,也没有增加任何东西,计数器无论如何都会增加,但只有+1:
所以,仍然在Mingw下:
http://localhost:8080/monkeys => Counting monkeys, 1 so far.
http://localhost:8080/monkeys => Counting monkeys, 3 so far.
http://localhost:8080/test => Another handler function that does not increment "views"
http://localhost:8080/donkeys => Counting donkeys, 6 so far.
在Linux下输出如下:
http://localhost:8080/monkeys => Counting monkeys, 1 so far.
http://localhost:8080/monkeys => Counting monkeys, 2 so far.
http://localhost:8080/test => Another handler function that does not increment "views"
http://localhost:8080/donkeys => Counting donkeys, 3 so far.
答案 0 :(得分:5)
我怀疑您所看到的行为是由于浏览器为您的网页请求了favicon,而不是由于Windows / mingw。如果您想知道,我正在使用6g ond Darwin,我的Firefox 3.6也在Mac OS X上运行。
为了强调我的怀疑,请尝试将以下内容添加到处理函数中:
fmt.Printf("Counting %s, %d so far.\n", r.URL.Path[1:], views)
然后您就可以看到所有到达您申请的请求。从刚刚启动的Firefox到URL http://localhost:8080/chuchichaestli的一个请求产生了这个输出:
Counting chuchichaestli, 1 so far.
Counting favicon.ico, 2 so far.
因为Firefox还会为你的页面请求favicon。
此外,即使可能存在多个并发请求,您也不会锁定/同步views
的访问权限。