HandleFunc被调用两次 [英] HandleFunc being called twice
问题描述
我在Go中遵循简单的web服务器示例。
我插入了一个 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 获取更多信息。
这篇关于HandleFunc被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!