Luís Soares
Luís Soares

Reputation: 6222

Setting a cookie with max age; max age is lost

So.. I have this unit test:

func TestCookieVoodoo(t *testing.T) {
    req := httptest.NewRequest("GET", "/", nil)

    cookie := http.Cookie{Name: "potato", MaxAge: 1000}

    req.AddCookie(&cookie)

    cookieCopy, _ := req.Cookie("potato")

    println(fmt.Sprintf("Cookie orig: %v", cookie))
    println(fmt.Sprintf("Cookie Copy: %v", *cookieCopy))

    t.Fail()
}

When running it, the output is:

Cookie orig: {potato    0001-01-01 00:00:00 +0000 UTC  1000 false false 0  []}
Cookie copy: {potato    0001-01-01 00:00:00 +0000 UTC  0 false false 0  []}

Why does it loose the max age? (same thing happens when setting other cookie fields) Thanks

Upvotes: 1

Views: 816

Answers (3)

Pan Ke
Pan Ke

Reputation: 579

Because the Request.AddCookie only add key and value to the cookie string. the function is:

func (r *Request) AddCookie(c *Cookie) {
    s := fmt.Sprintf("%s=%s", sanitizeCookieName(c.Name), sanitizeCookieValue(c.Value))
    if c := r.Header.Get("Cookie"); c != "" {
        r.Header.Set("Cookie", c+"; "+s)
    } else {
        r.Header.Set("Cookie", s)
    }
}

why?

  1. this is the definition of cookie-string in RFC 6265
  2. the Max-Age and other fields of cookie is used by client not server. they are config of client. for example: if the the cookie exprires, client doesn't send key=value to server. So the fields are ignored in request

Upvotes: 6

Jack Gore
Jack Gore

Reputation: 4252

If you look at the AddCookie code you can see it attaches a Cookie header to the request in the form <Name>=<Value>, or appends to an existing Cookie header ignoring all other fields of the Cookie struct except for Name and Value.

The Cookie header only has the notion of a Name and a Value, more information about the Cookie header can be found here.

A Set-Cookie header on the other hand would preserve all the fields of the Cookie struct, but this would typically set on an HTTP response. So it wouldn't really make sense to set this on your http.Request.

Upvotes: 3

Ewan
Ewan

Reputation: 15058

Looking at the Go implementation of AddCookie it is only taking the Name and Value fields.

I believe this is because the MaxAge is valid when sending a cookie in a Response but irrelevent when making a Request. Any cookies the client receives to submit with a request (as in your case) should be validated; valid cookies are then added with AddCookie and only their Keys and Values will be submitted with the request.

Upvotes: 1

Related Questions