英文:
Can't get cookie expiration time in golang
问题
我正在设置一个新的cookie
func f1(w http.ResponseWriter, r *http.Request) {
...
expire := time.Now().AddDate(0, 1, 0)
cookie := http.Cookie{"token", token, "/", "domain", expire, expire.Format(time.UnixDate), 86400, true, true, "token=" + token, []string{"token=" + token}}
http.SetCookie(w, &cookie)
然后我尝试获取它
func f2(w http.ResponseWriter, r *http.Request) {
...
cookie, err := r.Cookie("token")
fmt.Println(cookie.Value)
fmt.Println(cookie.Expires)
输出
valid_token_string
0001-01-01 00:00:00 +0000 UTC
值是我设置的相同,但过期时间为空。为什么?
英文:
I'm setting a new cookie
func f1(w http.ResponseWriter, r *http.Request) {
...
expire := time.Now().AddDate(0, 1, 0)
cookie := http.Cookie{"token", token, "/", "domain", expire, expire.Format(time.UnixDate), 86400, true, true, "token=" + token, []string{"token=" + token}}
http.SetCookie(w, &cookie)
Then i'm trying to get it
func f2(w http.ResponseWriter, r *http.Request) {
...
cookie, err := r.Cookie("token")
fmt.Println(cookie.Value)
fmt.Println(cookie.Expires)
Output
valid_token_string
0001-01-01 00:00:00 +0000 UTC
Value is the same i set, but Expires is empty.
Why?
答案1
得分: 15
这是HTTP的工作原理;expires属性只会在Set-Cookie响应头中发送,而不会在Cookie请求头中发送。Cookie请求头只包含cookie的名称和值,不包含任何其他元数据。
英文:
That's how HTTP works; the expires attribute is only sent with the Set-Cookie response header, not with the Cookie request header. The Cookie request header contains only the names and values of the cookies, not any other metadata.
答案2
得分: 0
我花了几分钟来弄清楚如何使用过期时间。
我觉得这个答案还不够。我想再添加两点:
- 服务器端的 cookie 可以设置额外的安全性(称为 http-only),使其只对服务器可见,而不对客户端的 JavaScript 可见,但它们仍然由浏览器存储以表示特定的客户端。参考
- 当后端设置了带有过期时间的 cookie 时,一旦 cookie 过期,浏览器就会删除它。
我相信这就是过期时间的工作原理。如果我们存储了一个会话令牌,后端无论如何都会检查会话是否过期。
英文:
I spent a few minutes to figure out how to use the expiry time.
I feel this answer is not enough.
I would like to add 2 more points to this:
- Server-side cookies can be set with additional security (called http-only) that makes them visible only to servers, not to client-side javascript, but they are still stored by browsers to represent a particular client. ref
- When backend sets this cookie with an expiration time, The browser deletes the cookie as soon as it is expired.
I believe that is how it works with expiration.
If we store a session token, backend is going to check for session expiry anyway.
答案3
得分: -2
如果您想查询到期时间,您应该将其视为不同的 cookie。
英文:
If you want to query the expiry, you should address it as a different cookie.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论