gin-gonic / contrib

Collection of middlewares created by the community

Home Page:https://gin-gonic.github.io/gin/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

session flashes not clearing

clanstyles opened this issue · comments

Session flashes aren't clearing I'm using go version go1.4.2 gccgo (GCC) 5.1.0 linux/amd64

There is only one "add flash" called and one "save" and then one "get flashes" and in Gorilla they're clearing, but they're not actually clearing on the next call. It removes them from the linked list but then a copy of gin somewhere must be taking over.

for me it worked by calling saving session

    v1.GET("/", func(c *gin.Context) {
        session := sessions.Default(c)
        flashes := session.Flashes() 
        session.Save() // <---- here it is!
        c.HTML(http.StatusOK, "index.html", gin.H{
            "flash":  flashes,
        })
    })

I'm doing the same thing, and I see the flashes rendered by my template like this:

{{ range $f := .flash }}
<div class="alert alert-danger">{{ $f }}</div>
{{ end }}

However, if I see the flash message, then navigate to another page, the flash message persists until I navigate again.

What am I doing wrong?

maybe call session.Save() // <---- here it is!? to save session with empty flashes

@vodolaz095 I'm already doing that quite liberally:

if u, _ := findUserByUsername(user.Username); u != nil {
		msg := fmt.Sprintf("User already exists: %s", user.Username)
		log.Println(msg)
		session.AddFlash(msg)
		err := session.Save()  // <---- see, right there :) 

		if err != nil {
			log.Println(err)
		}

		c.HTML(http.StatusOK, "signup.html", gin.H{
			"flash": session.Flashes(),
			"user":  user,
		})
		return
	}
commented

Have you tried saving just before the return (therefore after session.Flashes())?

This seems to work, though I'm not sure why.

commented

The principle of flashes is that you read them once then delete them. It's what sessions.Flashes() does but you need to save to remember the deletion.

@clanstyles Does this solve your original problem as well?