【发布时间】:2011-04-24 13:16:47
【问题描述】:
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.
【问题讨论】:
-
解决了!这不是 Go 的错。我的基于 Windows 的浏览器不断要求 favicon.ico 以及每个请求。谢谢@distributed!