spe
spe

Reputation: 1041

Can't get cookie expiration time in golang

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?

Upvotes: 11

Views: 5651

Answers (3)

Niranjan Shetty
Niranjan Shetty

Reputation: 155

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:

  1. 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
  2. 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.

Upvotes: 0

Nyta
Nyta

Reputation: 545

If you want to query the expiry, you should address it as a different cookie.

Upvotes: -2

user1804599
user1804599

Reputation:

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.

Upvotes: 15

Related Questions