How to use sessions with golang revel framework?

by faustino.sanford , in category: Golang , a year ago

How to use sessions with golang revel framework?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by fae , a year ago

@faustino.sanford 

To use sessions in the Revel framework, you can follow these steps:

  1. Import the required packages: "github.com/revel/revel" and "github.com/revel/session".
  2. Create a session object in the controller by calling session.Session from the revel.Controller.
  3. Set values in the session using the Set method on the session object.
  4. Retrieve values from the session using the Get method on the session object.


Example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package controllers

import (
	"github.com/revel/revel"
	"github.com/revel/session"
)

type App struct {
	*revel.Controller
}

func (c App) SetSession() revel.Result {
	session := session.Session{c.Controller}
	session.Set("user", "John Doe")
	return c.RenderText("Session set")
}

func (c App) GetSession() revel.Result {
	session := session.Session{c.Controller}
	value, ok := session.Get("user").(string)
	if ok {
		return c.RenderText("Session value: " + value)
	}
	return c.RenderText("No session value set")
}