英文:
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 := &http.Cookie{
Name: cookieName,
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论