I'm using gorilla/sessions in a toy app, and I want to use the FilesystemStore, but if I set the MaxAge
option to 0 for the store, it attempts to remove the session when saving it, but if the session is new, it doesn't have an ID:
sess, err := s.store.Get(r, "session-name")
if err != nil {
log.Printf("error getting session %v", err)
http.Error(w, "session", http.StatusInternalServerError)
return
}
sess.Values["name"] = r.FormValue("name")
if err = sess.Save(r, w); err != nil {
log.Printf("error saving session %v", err)
http.Error(w, "saving", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/view", http.StatusFound)
And the error I get is:
2019/10/15 09:22:03 error saving session remove sessions\session_: The system cannot find the file specified.
Looking at the Gorilla code, it seems the Gorilla code tries to delete the session from the store before determining if the session has an ID.
Is mine a problem with Gorilla, or with how I'm using it?
Things work fine when not setting MaxAge
to 0
, but then I'll have to manage the cookies myself.
If you check Save
method, you'll see that it tries to delete sessions with MaxAge <= 0
. You actually mark sessions that needs to be removed that way.
Since you're creating session with s.store.Get(r, "session-name")
, it will use MaxAge from that store, and you should set it to some value bigger than 0.
Doc for setting MaxAge says:
Individual sessions can be deleted by setting Options.MaxAge = -1 for that session.
But in Save you can see:
If the Options.MaxAge of the session is <= 0 then the session file will be deleted from the store path.
So, setting it to 0 is the same as setting it -1 or any other negative value.