donglang9880 2016-03-15 07:59
浏览 7
已采纳

运行一个简单的服务器,但计数器似乎增加了3,为什么呢? [重复]

This question already has an answer here:

I have this little server here. The intent is that if I visit localhost:8000/* it should increase counter by 1, and if I go to localhost:8000/count, it should show me the current number of counter.

A weird thing happening is that it seems like every time I visit localhost:8000, the counter goes up by 3. So I'd go to localhost:8000/count and the counter would be at 3, and then I visit localhost:8000, and then localhost:8000/count again, counter would now be at 6. Why does that happen? Is there something weird with net/http?

Also, why is it that when I refresh localhost:8000/count, the count goes up 1 by 1? The counter func doesn't increment count, yet count still goes up - why is that? Does handler get added to the localhost:8000/count route as well?

package main

import (
        "fmt"
        "log"
        "net/http"
        "sync"
)

var mu sync.Mutex
var count int

func main() {
        http.HandleFunc("/", handler)
        http.HandleFunc("/count", counter)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
        mu.Lock()
        count++
        mu.Unlock()
        fmt.Fprintf(w, "URL.Path = %q
", r.URL.Path)
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
        mu.Lock()
        fmt.Fprintf(w, "Count %d
", count)
        mu.Unlock()
}
</div>
  • 写回答

2条回答 默认 最新

  • duanlu1793 2016-03-15 08:11
    关注

    The extra requests are your browser trying to access /favicon.ico

    You can see this, for example, if you print the http.Request to stdout in your handler funcs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大