golang中的Session支持
生活随笔
收集整理的這篇文章主要介紹了
golang中的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 intsess := this.StartSession()count := sess.Get("count")if count == nil {intcount = 0} else {intcount = count.(int)}intcount = intcount + 1sess.Set("count", intcount)this.Data["Username"] = "astaxie"this.Data["Email"] = "astaxie@gmail.com"this.Data["Count"] = intcountthis.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)總結
以上是生活随笔為你收集整理的golang中的Session支持的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang自定义路由器设计
- 下一篇: golang表单及验证支持