英文:
How to remove a cookie in Go
问题
我已经设置了一个 cookie,并且在我的浏览器中可以看到它。我找不到任何方法来删除它。我尝试过的方法是:
deleteCookie, _ := r.Cookie("login")
deleteCookie.Value = ""
deleteCookie.MaxAge = -1
http.SetCookie(w, deleteCookie)
但是在运行这段代码后,cookie 仍然存在,并且保持着原始的值。
英文:
I've set a cookie and can see it in my browser. I couldn't find anyway to remove it. What I've tried was:
deleteCookie, _ := r.Cookie("login")
deleteCookie.Value = ""
deleteCookie.MaxAge = -1
http.SetCookie(w, deleteCookie)
But the cookie is still there with it's original value after running this code.
答案1
得分: 3
请尝试以下代码:
http.SetCookie(w, &http.Cookie{
Name: "login",
MaxAge: -1,
Expires: time.Now().Add(-100 * time.Hour), // 设置过期时间以适应旧版本的IE
Path: pathUsedToSetCookie,
})
其中,pathUsedToSetCookie
是你用于创建原始 cookie 的路径。请不要重用请求 cookie。Name
字段是你从请求 cookie 中所需的唯一字段,但你已经知道这一点了。
英文:
Try this:
http.SetCookie(w, &http.Cookie{
Name: "login",
MaxAge: -1,
Expires: time.Now().Add(-100 * time.Hour),// Set expires for older versions of IE
Path: pathUsedToSetCookie,
})
where pathUsedToSetCookie is whatever path you used to create the original cookie.
Do not reuse the request cookie. The Name field is the only field you need from the request cookie, but you know that already.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论