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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3