首页 > 文章列表 > HandleFunc 被调用两次

HandleFunc 被调用两次

golang
363 2023-03-08

问题内容

我在 Go 中关注一个[简​​单的 Web 服务器示例。](http://thenewstack.io/building-a-web-server-in- go/)

我插入了一条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)
}

问题是每当我在我的网络浏览器中加载端口 8000 时,这个函数都会被调用两次。这是一个问题,因为我打算在每次页面访问时增加一个计数器。通过这种行为,计数器会增加两次。OTOH,如果我这样做curl localhost:8000,它只会被调用一次。

我觉得我在这里想念的东西真的很愚蠢。

正确答案

只需记录请求。您将意识到您的浏览器也请求 /favicon.ico。

有关更多信息,请参阅https://en.wikipedia.org/wiki/Favicon