Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete a cookie with Go and http package?

Tags:

http

cookies

go

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?

like image 788
jjgames Avatar asked Jan 08 '23 14:01

jjgames


2 Answers

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.

like image 98
Bayta Darell Avatar answered Jan 14 '23 21:01

Bayta Darell


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)
like image 43
Juan Avatar answered Jan 14 '23 21:01

Juan