Sessions - Sharykhin/go-modular GitHub Wiki

Installation

To use session, first of all you should install appropriate package

go get github.com/gorilla/sessions
go get github.com/gorilla/context

Initialize

There is session component in the core. By default this component is imported in BaseController

import sessionComponent "go-modular/core/components/session"

To use session first of all you have to import session component. Then you have to initialize an instance of component in your action

session, _ := sessionComponent.Store.Get(req, "session")

Read data

To read data is pretty simple. Work with map[interface{}]interface{}

fmt.Println(session.Values["foo"])
fmt.Println(session.Values[42])

Save data

The saving data is similar to read, but with one an important step:

session.Values["foo"] = "bar"
session.Values[42] = 43
session.Save(req, res)

Flash messages

To add flash method you should use AddFlash method of session

session.AddFlash("Hello, flash messages world Error key!","error")
session.AddFlash("Hello, flash messages world Default key!")
session.Save(req, res)

The second parameter is type of flash message. By the way don't forget to save, such as all sessions data are persisted in cookies, you have to save you changes

BaseController provides special method GetFlashMessages, which returns flash messages. If key is nul, method will return flashes by using default key("_flash"). Method GetFlashMessages return slice of interface go []interface{}

flashErrorMessages := ctrl.GetFlashMessages(res,req,"error")
defaultFlash := ctrl.GetFlashMessages(res,req,nil)

if err := ctrl.RenderView(res,req, "index", []string{"include", "modules/admin:check"}, struct {
		TestData string		
		FlashMessage []interface{}
	}{
		TestData: "Test string",		
		FlashMessage: flashErrorMessages,
	}); err != nil {
		return err
	}

And use it in the template

{{ range $flash := .Data.FlashMessage}}
	<p style="color:#FF0000">{{$flash}}</p>
{{end}}