HandleFunc 被调用两次 [英] HandleFunc being called twice
问题描述
我正在使用 Go 中的简单网络服务器示例.
I am following a simple web server example in Go.
我插入了一个 log
语句,结果代码如下所示:
I inserted a log
statement so that the resulting code looks like below:
package main
import (
"io"
"log"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!")
log.Println("hello.")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", hello)
http.ListenAndServe(":8000", mux)
}
问题是,每当我在 Web 浏览器中加载端口 8000 时,此函数都会被调用两次.这是一个问题,因为我打算在每次访问页面时增加一个计数器.通过这种行为,计数器会增加两次.OTOH,如果我执行curl localhost:8000
,它只会被调用一次.
Problem is that whenever I load port 8000 in my web browser, this function is called twice. This is an issue because I intend to increment a counter on each page visit. With this behavior, counter gets incremented twice. OTOH, if I do curl localhost:8000
, it is called only once.
我觉得我在这里错过了一些非常愚蠢的事情.
I feel it's something really silly that I am missing here.
推荐答案
只需记录请求.您会发现您的浏览器也请求/favicon.ico.
Just log the requests. You will realize that your browser also requests /favicon.ico.
有关详细信息,请参阅 https://en.wikipedia.org/wiki/Favicon.
See https://en.wikipedia.org/wiki/Favicon for more information.
这篇关于HandleFunc 被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!