99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

Go Session支持

2022-05-13 16:43 更新

第六章的時候我們介紹過如何在Go語言中使用session,也實現(xiàn)了一個sessionManger,beego框架基于sessionManager實現(xiàn)了方便的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函數(shù)中增加如下代碼:

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框架開發(fā)的應用中使用session相當方便,基本上和PHP中調(diào)用session_start()類似。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號