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)
它没有closures,也没有增加任何东西,反正会增加,但只有+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.
我怀疑你所看到的行为是由于浏览器请求你的页面的图标,而不是由于Windows / mingw。 如果你想知道,我使用的是6g和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也会为你的页面请求图标。
此外,即使可能存在多个并发请求,您也不会锁定/同步对views
访问。