英文:
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”选项卡,在加载页面之前查看:
这是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:
(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/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论