I'm playing with the Go App Engine SDK and I'm trying to set/expires Cookies.
There is no problem by setting a Cookie, but it is impossible to make it expiring in the browser.
The app is a based on a negroni
instance:
func init() {
app := negroni.New()
app.UseHandler(Router())
http.Handle("/", app)
}
The router is a mux
instance:
func Router() *mux.Router {
r := mux.NewRouter()
subRouter := r.PathPrefix(PATH_PREFIX).Subrouter()
subRouter.HandleFunc("/sign", LoginHandler)
subRouter.HandleFunc("/userinfo", UserInfo)
subRouter.HandleFunc("/logout", Logout)
return r
}
The login handler is basic:
func LoginHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
u := user.Current(ctx)
if u == nil {
url, err := user.LoginURL(ctx, r.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
return
}
//COOKIE_ID = "SomeString"
cookie := &http.Cookie{Name: COOKIE_ID, Value: u.ID, Path: "/", MaxAge: 0}
http.SetCookie(w, cookie)
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusFound)
}
To expires the cookie:
func Logout(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
url, err := user.LogoutURL(ctx, "/")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
expiredCookie := &http.Cookie{Name: COOKIE_ID, MaxAge: -10, Expires: time.Now()}
http.SetCookie(w, expiredCookie)
w.Header().Set("Location", url)
w.WriteHeader(http.StatusFound)
}
I tried everything:
Full code: https://gist.github.com/yageek/78e43c83b56467fc8338
In any case, the cookie still remains in the navigator. What do I do wrong ?
Browsers store cookies for multiple paths. Set the path attribute on the cookie header to match the path attribute used to create the cookie.
Set maximum age to a negative value to clear the cookie. The maximum age attribute is not set on the header if equal to zero.
Some browsers do not understand the maximum age attribute. Set expiration to a time in the past for the benefit of those browsers.
expiredCookie := &http.Cookie{Path: "/", Name: COOKIE_ID, MaxAge: -1, Expires: time.Now().Add(-100 * time.Hour)}
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