How do you delete a cookie with Go and http package?

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

How do you delete a cookie with Go and http package?

问题

用户在使用http.SetCookie时设置了一个cookie,代码如下:

expire := time.Now().Add(7 * 24 * time.Hour)
cookie := http.Cookie{
    Name:    "name",
    Value:   "value",
    Expires: expire,
}
http.SetCookie(w, &cookie)

如果我想在以后的某个时间点删除这个cookie,应该如何正确操作?

英文:

A user has a cookie set when they visit using http.SetCookie like so:

expire := time.Now().Add(7 * 24 * time.Hour)
cookie := http.Cookie{
    Name:    "name",
    Value:   "value",
    Expires: expire,
}
http.SetCookie(w, &cookie)

If I want to remove this cookie at a later point, what is the correct way to do this?

答案1

得分: 9

你可以通过设置一个过去的时间来删除一个cookie,方法与设置cookie相同:

expire := time.Now().Add(-7 * 24 * time.Hour)
cookie := http.Cookie{
    Name:    "name",
    Value:   "value",
    Expires: expire,
}
http.SetCookie(w, &cookie)

注意-7的设置。

你也可以将MaxAge设置为负值。因为旧版本的IE不支持MaxAge,所以始终将Expires设置为过去的时间是很重要的。

英文:

You delete a cookie the same way you set a cookie, but with at time in the past:

expire := time.Now().Add(-7 * 24 * time.Hour)
cookie := http.Cookie{
    Name:    "name",
    Value:   "value",
    Expires: expire,
}
http.SetCookie(w, &cookie)

Note the -7.

You can also set MaxAge to a negative value. Because older versions of IE do not support MaxAge, it's important to always set Expires to a time in the past.

答案2

得分: 1

根据cookie.go的文档,MaxAge<0表示立即删除cookie。你可以尝试以下代码:

cookie := &http.Cookie{
    Name:   cookieName,
    Value:  "",
    Path:   "/",
    MaxAge: -1,
}
http.SetCookie(w, cookie)
英文:

According to the doc of cookie.go, MaxAge<0 means delete cookie now. You can try following codes:

cookie := &amp;http.Cookie{
	Name:   cookieName,
	Value:  &quot;&quot;,
	Path:   &quot;/&quot;,
	MaxAge: -1,
}
http.SetCookie(w, cookie)

huangapple
  • 本文由 发表于 2015年4月8日 03:36:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/29499843.html
匿名

发表评论

匿名网友

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

确定