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

用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条)

报告相同问题?

悬赏问题

  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区