Windows中的不稳定行为?

Seb*_*oli 0 windows mingw go

  Update:  The question title can be misleading.  This was not Go's fault at all.
           See the first comment or the accepted answer.
Run Code Online (Sandbox Code Playgroud)

以下代码(好吧,几乎相同)计算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++
    }
}
*/
Run Code Online (Sandbox Code Playgroud)

在Mingw下:

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.
Run Code Online (Sandbox Code Playgroud)

这可能是个错误吗?

跟进:

实际上,如果我为另一个页面定义一个额外的处理程序,例如:

   http.HandleFunc("/test", testPageHandler)
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

在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.
Run Code Online (Sandbox Code Playgroud)

dis*_*ted 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)
Run Code Online (Sandbox Code Playgroud)

然后,您可以看到所有到达您的应用程序的请求.从刚刚启动的Firefox到URL http:// localhost:8080/chuchichaestli的一个请求产生以下输出:

Counting chuchichaestli, 1 so far.
Counting favicon.ico, 2 so far.
Run Code Online (Sandbox Code Playgroud)

因为Firefox还会为你的go页面请求favicon.

此外,views即使可能存在多个并发请求,您也不会锁定/同步访问权限.