计数增加了2,预期为1。

huangapple go评论79阅读模式
英文:

Count increased by 2, expecting 1

问题

我正在按照书上的例子进行操作。它假设在输入 http://localhost:8080/xxx 时会增加计数,并在输入 http://localhost:8080/count 时返回计数值。

以下是代码:

var count int
var mu sync.Mutex

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/count", counter)
    log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

func handler(w http.ResponseWriter, req *http.Request) {
    mu.Lock()
    fmt.Fprintf(w, "Count before: %d\n", count)
    count++
    fmt.Fprintf(w, "Count after: %d\n", count)
    mu.Unlock()
    fmt.Fprintf(w, "URL.Path = %q\n", req.URL.Path)
}

func counter(w http.ResponseWriter, req *http.Request) {
    mu.Lock()
    fmt.Fprintf(w, "Count: %d\n", count)
    mu.Unlock()
}

然而,当我打开 http://localhost:8080 并刷新页面时,每次计数增加的是2而不是1。这是 Chrome 浏览器的某个特性吗?

英文:

I am following the example from the book. It supposes to increase the count when type something http://localhost:8080/xxx and return the count number when type http://localhost:8080/count

The code is below

var count int
var mu sync.Mutex
func main() {
        http.HandleFunc("/", handler)
        http.HandleFunc("/count", counter)
        log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
func handler(w http.ResponseWriter, req *http.Request) {
        mu.Lock()
        fmt.Fprintf(w, "Count before: %d\n", count)
        count++
        fmt.Fprintf(w, "Count after: %d\n", count)
        mu.Unlock()
        fmt.Fprintf(w, "URL.Path = %q\n", req.URL.Path)
}
func counter(w http.ResponseWriter, req *http.Request) {
        mu.Lock()
        fmt.Fprintf(w, "Count: %d\n", count)
        mu.Unlock()
}

However, when I open http://localhost:8080 and refresh, count is increase by 2 each time instead of 1. Is this some feature in Chrome?

答案1

得分: 3

Chrome会自动尝试获取网站的favicon图标,这会导致计数器再次增加。

你可以通过按下F12并转到“Network”选项卡,在加载页面之前查看:

计数增加了2,预期为1。

这是Chrome开发工具的一部分:https://developers.google.com/web/tools/chrome-devtools/

要测试这段代码,我建议使用curl命令,如下:curl -XGET http://localhost:8080/

英文:

Chrome automatically tries to fetch the favicon, increasing the counter a second time

You can see it by pressing F12 and going to the "Network" tab before loading the page:

计数增加了2,预期为1。

(this is part of the Chrome dev tools: https://developers.google.com/web/tools/chrome-devtools/)

To test that exact code, I'd advise using curl like this : curl -XGET http://localhost:8080/

huangapple
  • 本文由 发表于 2015年11月28日 12:47:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/33967801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定