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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With