Repository navigation
Sessions
Caleb Hiebert edited this page Nov 16, 2018
·
2 revisions
Gobbl comes with session middleware. Here is a code snippet showing how to use the session middleware:
func main() {
gobblr := gbl.New()
gobblr.Use(gbl.RequestExtractionMiddleware())
// We need to create a session store to keep our session data in
// The session store is responsible for storing and retrieving data
sessionStore := sess.MemoryStore()
// Make sure to add the session middleware
// The session middleware takes the session store as an argument
gobblr.Use(sess.Middleware(sessionStore))
gobblr.Use(func(c *gbl.Context) {
basicResponse := c.R.(*gbl.BasicResponse)
// Sessions are interacted with via flags
// All session flags start with "sess:"
// Any flag with the prefix "sess:" will be saved to the session
if !c.HasFlag("sess:message-count") {
c.Flag("sess:message-count", 0)
}
if !c.HasFlag("sess:name") {
c.Flag("sess:name", "Joe")
}
// Increment our message count by 1
// The session is automatically saved when the request is finished
c.Flag("sess:message-count", c.GetIntFlag("sess:message-count")+1)
// We can delete session variables simply by clearing their flags
// This will clear the message-count variable when the user types "clear"
if c.Request.Text == "clear" {
basicResponse.Text("Cleared the session")
c.ClearFlag("sess:message-count")
}
basicResponse.Text(
fmt.Sprintf("Hello %s, you have sent: %d messages",
c.GetFlag("sess:name"),
c.GetFlag("sess:message-count")))
})
ci := gbl.ConsoleIntegration{}
ci.Listen(gobblr)
}