代码之家  ›  专栏  ›  技术社区  ›  Sebastián Grignoli

Windows中的异常行为?

  •  0
  • Sebastián Grignoli  · 技术社区  · 16 年前
      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)
    

    所以,在明明之下:

    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.
    
    1 回复  |  直到 9 年前
        1
  •  5
  •   distributed    16 年前

    我怀疑您看到的行为是由于浏览器请求您的页面的favicon,而不是由于Windows/mingw。如果你想知道,我使用的是6gonddarwin,我的Firefox 3.6也在Mac OS X上运行。

    为了强调我的怀疑,请尝试在handler函数中添加以下内容:

    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访问你的go页面。

    此外,您没有锁定/同步访问 views