Search code examples
sessiongomartini

golang martini session.Set not setting any value


There isn't much context with this because it really is a situation where something should work, but it just doesn't.

I am using the martini framework. In one handler I'm using this:

session.Set("deployed", "true")
r.Redirect("/myOtherURL", http.StatusSeeOther)

Whereby 'session' is the sessions.Session object passed through to the handler. In the handler that loads myOtherURL, I'm using session.Get but nothing is being returned. I printed out all of the session content and the 'deployed' is not present.

What could be causing this problem? What could I possibly be missing out? I would give more context if I could but it really is as simple as this.


Solution

  • Just to extend on my comment/help others in the future:

    • When you set a cookie without an explicit Path value, the cookie takes on the current path.
    • Cookies are only sent for that path and paths below - not above - e.g.

      1. Cookie set for /modules when you implicitly set it for the first time via session.Set(val, key)
      2. Cookie is sent for /modules, /modules/all and /modules/detail/12
      3. Cookie is NOT sent for /about or /

    This can be fixed by explicitly setting the path:

    var store = sessions.NewCookieStore([]byte("secret123"))
    
    func main() {
        store.Options.Path = "/"
        ...
    }
    

    Be aware that you may not want to send a cookie for all routes (which is what / will do) - so use judgement.