Beego之Session
beego內置了session模塊,目前session模塊支持的后端引擎包括memory、cookie、file、 mysq|、 redis、 couchbase、 memcache、 postgres. 用戶也可以根據相應的interface實現自己的引擎。
一、Session的使用
Beego默認關閉Session,要想使用也相當方便,可以通過代碼的方式,只要在main入口函數中設置如下:
beego.BConfig.WebConfig.Session.SessionOn = true
或者通過配置文件配置如下:
sessionon = true
二、session 的常用方法:
- SetSession(name string, value interface{})
- GetSession(name string) interface{}
- DelSession(name string)
- SessionRegeneratelD()
- DestroySession)
三、實例操作
我們借助於之前的項目案例。
3.1 設置main()方法,打開session
修改main.go中的main()方法:
func main() { beego.BConfig.WebConfig.Session.SessionOn = true beego.Run() }
3.2 設置session
修改testlogin.go文件,我們在post表單登錄的時候,設置cookie的同時,也設置session:
func (c *TestLoginController) Post() { u := UserInfo{} if err := c.ParseForm(&u); err != nil { log.Panic(err) } //設置cookie c.Ctx.SetCookie("username",u.Username,100,"/") c.Ctx.SetCookie("password",u.Password,100,"/") //設置session c.SetSession("username",u.Username) c.SetSession("password",u.Password) c.Ctx.WriteString("Username:" + u.Username + ",Password:" + u.Password) }
3.3 獲取session
修改testinput.go文件,我們在get訪問testinput的時候,獲取session:
func (c *TestInputController) TestInputGet() { //name := c.GetString("name") //c.Ctx.WriteString("<html>"+name+"<br/>") // //idstr:=c.Input().Get("id") //c.Ctx.WriteString(idstr+"</html>") // //id,_:=strconv.Atoi(idstr) //fmt.Println(id) //讀取session username := c.GetSession("username") password := c.GetSession("password") if nameString, ok := username.(string); ok && nameString != "" { c.Ctx.WriteString("Username:" + username.(string) + ",Password:" + password.(string)) } else { c.Ctx.WriteString(`<html><form action="http://127.0.0.1:9527/testinput" method="post"> 用戶名:<input type ="text" name="Username" /> <br/> 密   碼:<input type="password" name="pwd"> <br/> <input type="submit" value="提交"> </form></html>`) } }
然后重新啟動項目,並打開瀏覽器輸入:http://127.0.0.1:9527/testlogin
因為首次登錄,瀏覽器運行如下:
接下來,我們輸入用戶名和密碼:
此時,已經通過post請求,執行對應的Post()方法,設置了cookie和session。
接下來我們在瀏覽器中輸入:http://127.0.0.1:9527/testinput
瀏覽器運行結果如下:
因為可以獲取到session,所以直接顯示了登錄信息。
3.4 刪除Session
c.GetSession(“username”),如果沒有獲取到session,會返回nil,和cookie不一樣,getCookie返回空字符串。
- Session是一段保存在服務器上的一段信息,當客戶端第一次訪問服務器時創建。同時也創建一個名為beegosessionID,值為創建Session的id的Cookie
- 這個beegosessionID對應服務器中的一個Session對象,通過它就可以獲取到保存用戶信息的Session
通過c.DelSession("password")和c.DestroySession()均可以刪除Session,其區別在於DelSession刪除指定的Session, DestroySession刪除所有session。
另外,可以通過beego.BConfig.WebConfig.Session.SessionName 設置,如果在配置文件和主函數都設置了,主函數優先,因為beego先加載配置文件后執行主函數,所以主函數中設置的內容回對配置文件中設置的內容進行覆蓋。