W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
第六章的時候我們介紹過如何在Go語言中使用session,也實現(xiàn)了一個sessionManger,beego框架基于sessionManager實現(xiàn)了方便的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
}
通過上面的代碼我們可以看到,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,主要分兩個步驟:
獲取session對象
//獲取對象,類似PHP中的session_start()
sess := this.StartSession()
使用session進行一般的session值操作
//獲取session值,類似PHP中的$_SESSION["count"]
sess.Get("count")
//設置session值
sess.Set("count", intcount)
從上面代碼可以看出基于beego框架開發(fā)的應用中使用session相當方便,基本上和PHP中調(diào)用session_start()
類似。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: