doucai7294 2019-04-04 11:26
浏览 94
已采纳

用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)
}
  • 写回答

2条回答 默认 最新

  • douwulu2576 2019-04-04 11:31
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?