In chapter 6, we introduced some basic concepts pertaining to sessions in Go, and we implemented a session manager. The Beego framework uses this session manager to implement some convenient session-handling functionality.
Integrating sessions
Beego handles sessions mainly according to the following global variables:
// related to session
SessionOn bool // whether or not to open the session module. Defaults to false.
SessionProvider string // the desired session backend processing module. Defaults to an in-memory sessionManager
SessionName string // the name of the client saved cookies
SessionGCMaxLifetime int64 // cookie validity
GlobalSessions *session.Manager// global session controller
Of course, the values of these variables shown above need to be initialized. You can also use the values from the following configuration file code to set these values:
if ar, err := AppConfig.Bool("sessionon"); err != nil {
SessionOn = false
} else {
SessionOn = ar
}
if ar := AppConfig.String("sessionprovider"); ar == "" {
SessionProvider = "memory"
} else {
SessionProvider = ar
}
if ar := AppConfig.String("sessionname"); ar == "" {
SessionName = "beegosessionID"
} else {
SessionName = ar
}
if ar, err := AppConfig.Int("sessiongcmaxlifetime"); err != nil && ar != 0 {
int64val, _ := strconv.ParseInt(strconv.Itoa(ar), 10, 64)
SessionGCMaxLifetime = int64val
} else {
SessionGCMaxLifetime = 3600
}
Add the following code in the beego.Run function:
if SessionOn {
GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime)
go GlobalSessions.GC()
}
As long as SessionOn is set to true, it will open the session by default with an independent goroutine session handler
In order to facilitate our custom Controller quickly using session, the author beego.Controller provides the following methods:
To assist us in quickly using sessions in a custom Controller, beego.Controller provides the following method:
The code above shows how to use sessions in the controller logic. The process can be divided into two steps:
Getting session object
// Get the object, similar in PHP session_start()
sess:= this.StartSession()
Using the session for general operations
// Get the session values , similar in PHP $ _SESSION ["count"]
sess.Get("count")
// Set the session value
sess.Set("count", intcount)
As you can see, applications based on the Beego framework can easily implement sessions. The process is very similar to calling session_start() in PHP applications.