Files
build-web-application-with-…/en/14.2.md
2016-09-13 21:42:49 +08:00

3.3 KiB
Raw Blame History

14.2 Session支持

第六章的时候我们介绍过如何在Go语言中使用session也实现了一个sessionMangerbeego框架基于sessionManager实现了方便的session处理功能。

session集成

beego中主要有以下的全局变量来控制session处理

//related to session 
SessionOn            bool   // 是否开启session模块默认不开启
SessionProvider      string // session后端提供处理模块默认是sessionManager支持的memory
SessionName          string // 客户端保存的cookies的名称
SessionGCMaxLifetime int64  // cookies有效期

GlobalSessions *session.Manager //全局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 {
	int64val, _ := strconv.ParseInt(strconv.Itoa(ar), 10, 64)
	SessionGCMaxLifetime = int64val
} else {
	SessionGCMaxLifetime = 3600
}	

在beego.Run函数中增加如下代码

if SessionOn {
	GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime)
	go GlobalSessions.GC()
}

这样只要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
}		

session使用

通过上面的代码我们可以看到beego框架简单地继承了session功能那么在项目中如何使用呢

首先我们需要在应用的main入口处开启session

beego.SessionOn = true

然后我们就可以在控制器的相应方法中如下所示的使用session了

func (this *MainController) Get() {
	var intcount int
	sess := this.StartSession()
	count := sess.Get("count")
	if count == nil {
		intcount = 0
	} else {
		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主要分两个步骤

  1. 获取session对象

     //获取对象,类似PHP中的session_start()
     sess := this.StartSession()
    
  2. 使用session进行一般的session值操作

     //获取session值类似PHP中的$_SESSION["count"]
     sess.Get("count")
    
     //设置session值
     sess.Set("count", intcount)
    

从上面代码可以看出基于beego框架开发的应用中使用session相当方便基本上和PHP中调用session_start()类似。