如何在Go中删除一个cookie

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年1月21日 14:17:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/28060767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定