【问题标题】:Running a simple server, but the counter seems to go up by 3, why? [duplicate]运行一个简单的服务器,但计数器似乎增加了 3,为什么? [复制]
【发布时间】: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/countcounter 现在是 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(在文件中,或在标准输出中)。您可能会收到额外的网站图标等请求。
  • 不知道为什么我没有想到这一点。谢谢

标签: http go


【解决方案1】:

额外的请求是您的浏览器试图访问 /favicon.ico

您可以看到这一点,例如,如果您在处理程序函数中将 http.Request 打印到标准输出。

【讨论】:

  • 好的。我正在记录它,这就是我发现的:每次我的浏览器点击 url 时,它也会请求一个 favicon,就像你 @aedolon 和 @simo 说的那样。另外,localhost:8000/count", handler` 和 counter 似乎都被命中了。有趣的东西。
  • 您的浏览器可能(不同的浏览器可能表现不同)在访问 /count 时也会尝试抓取 favicon,但 favicon 请求都由 handler 处理,因为“/”是最好的并且只匹配“/favicon.ico”。
  • @LeibnizMan:再次检查加载“/count”页面时点击的所有网址。也许您的浏览器会发送额外的请求。 favicon.ico 请求的数量和重复次数取决于您的浏览器以及它如何缓存内容:在我的 PC (firefox - linux) 上,我只在第一页加载时看到 +3 步骤;之后,计数器“按预期”递增。
【解决方案2】:

问题是您的处理程序正在提供额外的静态内容,例如 favicon 等。如果您记录请求,您会看到您的浏览器可能也在请求 /favicon.ico,它被传递给同一个处理程序。

提供静态内容的一种方法是创建自己的ServeMux

package main

import (
    "fmt"
    "net/http"
    "strings"
)   

var chttp = http.NewServeMux()

func main() {

    chttp.Handle("/", http.FileServer(http.Dir("./")))

    http.HandleFunc("/", HomeHandler) // homepage
    http.ListenAndServe(":8080", nil)
}   

func HomeHandler(w http.ResponseWriter, r *http.Request) {

    if (strings.Contains(r.URL.Path, ".")) {
        chttp.ServeHTTP(w, r)
    } else {
        fmt.Fprintf(w, "HomeHandler")
    }   
} 

Serve homepage and static content from root

【讨论】:

  • 感谢您的回答。我接受了@Aedolon,因为他是第一个 - 但据我所知,你同样正确:D
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 2020-02-21
  • 1970-01-01
  • 2020-05-28
  • 2021-05-09
  • 1970-01-01
相关资源
最近更新 更多