Saving session after response?


#1

I’m using echo-contrib/session to store some session data. As I am doing server side rendering, I want to pass my session data to the renderer, along those lines:

sess, err := session.Get("session", c)
// check err
return c.Render(http.StatusOK, "home", sess)

But here is the catch: in my template, I might call .Flashes() to display the flashes stored in the session - but calling this method is supposed to remove the flashes from the session, so I need to save the session afterwards:

err := sess.Save(c.Request(), c.Response())
// check err

Unfortunately, I’m already inside c.Render(), which is the last call before ending the handler. Is there a way to save the modified session somehow?


#2

I would pass to the template a proper data structure instead of the session and move the logic that determines if the flashes are shown outside the template.


#3

Following this question. Read something similar to this in the comments section of this website’s article

I am also facing the same issue but passing a data structure makes the all over stuff hectic.


#4

@jake1santiago Well, here is how I circumvented the problem:

I wrote a middleware that extracts the flashes and the values from the session and stores them in the context. That way both are accessibles with c.Get("flashes") and c.Get("values"). Then, I simply pass the whole context to my template, so I can access my flashes with {{ .Get "flashes" }}.

But there is a catch: the middleware will extract flashes from the session everytime a request is processed, but sometimes you don’t want that. For example, if you are doing POST + 302 Redirect to manage form inputs, your flashes my get eaten by the first request and won’t appear. My workaround was to skip this middleware for all but GET requests.