14.2 Session支持
beego中主要有以下的全局变量来控制session处理:
当然上面这些变量需要初始化值,也可以按照下面的代码来配合配置文件以设置这些值:
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 {
SessionGCMaxLifetime = int64val
} else {
SessionGCMaxLifetime = 3600
}
这样只要SessionOn设置为true,那么就会默认开启session功能,独立开一个goroutine来处理session。
为了方便我们在自定义Controller中快速使用session,作者在beego.Controller
中提供了如下方法:
func (c *Controller) StartSession() (sess session.Session) {
sess = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request)
return
}
首先我们需要在应用的main入口处开启session:
然后我们就可以在控制器的相应方法中如下所示的使用session了:
func (this *MainController) Get() {
var intcount int
sess := this.StartSession()
count := sess.Get("count")
if count == nil {
intcount = count.(int)
}
intcount = intcount + 1
sess.Set("count", intcount)
this.Data["Username"] = "astaxie"
this.Data["Email"] = "astaxie@gmail.com"
this.Data["Count"] = intcount
this.TplNames = "index.tpl"
}
- 获取session对象
- 使用session进行一般的session值操作
//获取session值,类似PHP中的$_SESSION["count"]
sess.Get("count")
//设置session值
sess.Set("count", intcount)
从上面代码可以看出基于beego框架开发的应用中使用session相当方便,基本上和PHP中调用类似。
- 上一节: 静态文件支持