我正在关注Go中的simple web server example。HandleFunc被调用两次
我插入了log
语句,以便生成的代码看起来像下面:
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
,它只被调用一次。
我觉得这是真的很傻,我在这里失踪。