14.2 Session支持

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

    当然上面这些变量需要初始化值,也可以按照下面的代码来配合配置文件以设置这些值:

    1. if ar, err := AppConfig.Bool("sessionon"); err != nil {
    2. SessionOn = false
    3. } else {
    4. SessionOn = ar
    5. }
    6. if ar := AppConfig.String("sessionprovider"); ar == "" {
    7. SessionProvider = "memory"
    8. } else {
    9. SessionProvider = ar
    10. }
    11. if ar := AppConfig.String("sessionname"); ar == "" {
    12. SessionName = "beegosessionID"
    13. } else {
    14. SessionName = ar
    15. if ar, err := AppConfig.Int("sessiongcmaxlifetime"); err != nil && ar != 0 {
    16. SessionGCMaxLifetime = int64val
    17. } else {
    18. SessionGCMaxLifetime = 3600
    19. }

    这样只要SessionOn设置为true,那么就会默认开启session功能,独立开一个goroutine来处理session。

    为了方便我们在自定义Controller中快速使用session,作者在beego.Controller中提供了如下方法:

    1. func (c *Controller) StartSession() (sess session.Session) {
    2. sess = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request)
    3. return
    4. }

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

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

    1. func (this *MainController) Get() {
    2. var intcount int
    3. sess := this.StartSession()
    4. count := sess.Get("count")
    5. if count == nil {
    6. intcount = count.(int)
    7. }
    8. intcount = intcount + 1
    9. sess.Set("count", intcount)
    10. this.Data["Username"] = "astaxie"
    11. this.Data["Email"] = "astaxie@gmail.com"
    12. this.Data["Count"] = intcount
    13. this.TplNames = "index.tpl"
    14. }
    1. 获取session对象
    1. 使用session进行一般的session值操作
    1. //获取session值,类似PHP中的$_SESSION["count"]
    2. sess.Get("count")
    3. //设置session值
    4. sess.Set("count", intcount)

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