【发布时间】:2016-06-30 13:13:22
【问题描述】:
我这里有这个小服务器。目的是,如果我访问 localhost:8000/*,它应该将 counter 增加 1,如果我访问 localhost:8000/count,它应该显示counter 的当前数量。
发生的一件奇怪的事情是,似乎每次我访问 localhost:8000 时,计数器都会增加 3。所以我会去 localhost:8000/count 并且 counter 会在 3,然后我访问localhost:8000,然后又是localhost:8000/count,counter 现在是 6。为什么会这样? net/http 有什么奇怪的地方吗?
另外,为什么当我刷新localhost:8000/count 时,计数会增加 1 比 1? counter 函数不会增加 count,但 count 仍然会上升 - 为什么会这样? handler 是否也被添加到 localhost:8000/count 路由中?
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\n", 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\n", count)
mu.Unlock()
}
【问题讨论】:
-
记录命中“处理程序”函数的 url(在文件中,或在标准输出中)。您可能会收到额外的网站图标等请求。
-
不知道为什么我没有想到这一点。谢谢