4

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?

jjgames
  • 87
  • 1
  • 8
  • 1
    possible duplicate of [How to delete cookie](http://stackoverflow.com/questions/27671061/how-to-delete-cookie) – Dave C Apr 07 '15 at 19:43
  • 1
    I'd eat a cookie rather than delete it. /omnomnom –  Apr 07 '15 at 20:49

2 Answers2

9

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
1

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)
Juan
  • 11
  • 3