用Cookie创建一个计数器

I have used the below code to create a counter using cookies. But I guess there is an issue with this http.HandleFunc("/", foo) function. Ideally the counter should be incremented only when the request is http:localhost:8080 or http:localhost:8080/.

But the count is getting incremented even if I type some random text after "/" (ex: http:localhost:8080/abcd).

func main() {
    http.HandleFunc("/", foo)
    http.Handle("/favicon.ico", http.NotFoundHandler())
    http.ListenAndServe(":8080", nil)
}

func foo(res http.ResponseWriter, req *http.Request) {
    cookie, err := req.Cookie("my-cookie-counter")

    if err == http.ErrNoCookie {
        cookie = &http.Cookie{
            Name:  "my-cookie-counter",
            Value: "0",
        }
    }
    count, err := strconv.Atoi(cookie.Value)
    if err != nil {
        log.Fatalln(err)
    }
    count++
    cookie.Value = strconv.Itoa(count)
    http.SetCookie(res, cookie)
    io.WriteString(res, cookie.Value)
}

This is the documented behavior of the / path when handled by the standard library's ServeMux, as you are doing.

Your options are:

  1. Use a different router, which does exact matching.
  2. In your handler, check for the expected path.
http.HandleFunc("/", foo)

This works as a prefix matcher. It will match root and everything below. One way to make it match only the root is check r.URL.Path in your handler and not do work if the path is not the root.