Reputation: 6222
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
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?
cookie-string
in RFC 6265
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 requestUpvotes: 6
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
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