W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
這個文檔是 session 獨立模塊,即你單獨拿這個模塊應用于其他應用中,如果你想在 beego 中使用 session,請查看文檔session 控制
session 模塊是用來存儲客戶端用戶,session 模塊目前只支持 cookie 方式的請求,如果客戶端不支持 cookie,那么就無法使用該模塊。
session 模塊參考了 database/sql 的引擎寫法,采用了一個接口,多個實現(xiàn)的方式。目前實現(xiàn)了 memory、file、Redis 和 MySQL 四種存儲引擎。
通過下面的方式安裝 session:
go get github.com/astaxie/beego/session
首先你必須導入包:
import (
"github.com/astaxie/beego/session"
)
然后你初始化一個全局的變量用來存儲 session 控制器:
var globalSessions *session.Manager
接著在你的入口函數(shù)中初始化數(shù)據(jù):
func init() {
sessionConfig := &session.ManagerConfig{
CookieName:"gosessionid",
EnableSetCookie: true,
Gclifetime:3600,
Maxlifetime: 3600,
Secure: false,
CookieLifeTime: 3600,
ProviderConfig: "./tmp",
}
globalSessions, _ = session.NewManager("memory",sessionConfig)
go globalSessions.GC()
}
NewManager 函數(shù)的參數(shù)的函數(shù)如下所示
最后我們的業(yè)務邏輯處理函數(shù)中可以這樣調用:
func login(w http.ResponseWriter, r *http.Request) {
sess, _ := globalSessions.SessionStart(w, r)
defer sess.SessionRelease(w)
username := sess.Get("username")
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
} else {
sess.Set("username", r.Form["username"])
}
}
globalSessions 有多個函數(shù)如下所示:
返回的 session 對象是一個 Interface,包含下面的方法
上面已經(jīng)展示了 memory 的設置,接下來我們看一下其他三種引擎的設置方式:
在開發(fā)應用中,你可能需要實現(xiàn)自己的 session 引擎,beego 的這個 session 模塊設計的時候就是采用了 interface,所以你可以根據(jù)接口實現(xiàn)任意的引擎,例如 memcache 的引擎。
type SessionStore interface {
Set(key, value interface{}) error //set session value
Get(key interface{}) interface{} //get session value
Delete(key interface{}) error //delete session value
SessionID() string //back current sessionID
SessionRelease() // release the resource & save data to provider
Flush() error //delete all data
}
type Provider interface {
SessionInit(maxlifetime int64, savePath string) error
SessionRead(sid string) (SessionStore, error)
SessionExist(sid string) bool
SessionRegenerate(oldsid, sid string) (SessionStore, error)
SessionDestroy(sid string) error
SessionAll() int //get all active session
SessionGC()
}
最后需要注冊自己寫的引擎:
func init() {
Register("own", ownadaper)
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: