【问题标题】:Erratic behavior in Windows?Windows中的不稳定行为?
【发布时间】: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!

标签: windows go mingw


【解决方案1】:

我怀疑您看到的行为是由于浏览器为您的页面请求网站图标,而不是由于 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 的访问。

【讨论】:

猜你喜欢
  • 2011-01-27
  • 2019-08-02
  • 1970-01-01
  • 2012-04-24
  • 2023-03-09
  • 2015-08-19
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多