Files
build-web-application-with-…/zh-tw/14.2.md
2019-02-26 01:40:54 +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()
  1. 使用session進行一般的session值操作

	//取得session值類似PHP中的$_SESSION["count"]
	sess.Get("count")

	//設定session值
	sess.Set("count", intcount)

從上面程式碼可以看出基於beego框架開發的應用中使用session相當方便基本上和PHP中呼叫session_start()類似。