通過上一小節(jié)的介紹,我們知道session是在服務器端實現(xiàn)的一種用戶和服務器之間認證的解決方案,目前Go標準包沒有為session提供任何支持,這小節(jié)我們將會自己動手來實現(xiàn)go版本的session管理和創(chuàng)建。
session的基本原理是由服務器為每個會話維護一份信息數(shù)據(jù),客戶端和服務端依靠一個全局唯一的標識來訪問這份數(shù)據(jù),以達到交互的目的。當用戶訪問Web應用時,服務端程序會隨需要創(chuàng)建session,這個過程可以概括為三個步驟:
以上三個步驟中,最關(guān)鍵的是如何發(fā)送這個session的唯一標識這一步上??紤]到HTTP協(xié)議的定義,數(shù)據(jù)無非可以放到請求行、頭域或Body里,所以一般來說會有兩種常用的方式:cookie和URL重寫。
通過上面session創(chuàng)建過程的講解,讀者應該對session有了一個大體的認識,但是具體到動態(tài)頁面技術(shù)里面,又是怎么實現(xiàn)session的呢?下面我們將結(jié)合session的生命周期(lifecycle),來實現(xiàn)go語言版本的session管理。
我們知道session管理涉及到如下幾個因素
接下來我將講解一下我關(guān)于session管理的整個設計思路以及相應的go代碼示例:
定義一個全局的session管理器
type Manager struct {
cookieName string //private cookiename
lock sync.Mutex // protects session
provider Provider
maxlifetime int64
}
func NewManager(provideName, cookieName string, maxlifetime int64) (*Manager, error) {
provider, ok := provides[provideName]
if !ok {
return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
}
return &Manager{provider: provider, cookieName: cookieName, maxlifetime: maxlifetime}, nil
}
Go實現(xiàn)整個的流程應該也是這樣的,在main包中創(chuàng)建一個全局的session管理器
var globalSessions *session.Manager
//然后在init函數(shù)中初始化
func init() {
globalSessions, _ = NewManager("memory","gosessionid",3600)
}
我們知道session是保存在服務器端的數(shù)據(jù),它可以以任何的方式存儲,比如存儲在內(nèi)存、數(shù)據(jù)庫或者文件中。因此我們抽象出一個Provider接口,用以表征session管理器底層存儲結(jié)構(gòu)。
type Provider interface {
SessionInit(sid string) (Session, error)
SessionRead(sid string) (Session, error)
SessionDestroy(sid string) error
SessionGC(maxLifeTime int64)
}
那么Session接口需要實現(xiàn)什么樣的功能呢?有過Web開發(fā)經(jīng)驗的讀者知道,對Session的處理基本就 設置值、讀取值、刪除值以及獲取當前sessionID這四個操作,所以我們的Session接口也就實現(xiàn)這四個操作。
type Session 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
}
以上設計思路來源于database/sql/driver,先定義好接口,然后具體的存儲session的結(jié)構(gòu)實現(xiàn)相應的接口并注冊后,相應功能這樣就可以使用了,以下是用來隨需注冊存儲session的結(jié)構(gòu)的Register函數(shù)的實現(xiàn)。
var provides = make(map[string]Provider)
// Register makes a session provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, provider Provider) {
if provider == nil {
panic("session: Register provide is nil")
}
if _, dup := provides[name]; dup {
panic("session: Register called twice for provide " + name)
}
provides[name] = provider
}
Session ID是用來識別訪問Web應用的每一個用戶,因此必須保證它是全局唯一的(GUID),下面代碼展示了如何滿足這一需求:
func (manager *Manager) sessionId() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}
我們需要為每個來訪用戶分配或獲取與他相關(guān)連的Session,以便后面根據(jù)Session信息來驗證操作。SessionStart這個函數(shù)就是用來檢測是否已經(jīng)有某個Session與當前來訪用戶發(fā)生了關(guān)聯(lián),如果沒有則創(chuàng)建之。
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
manager.lock.Lock()
defer manager.lock.Unlock()
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := manager.sessionId()
session, _ = manager.provider.SessionInit(sid)
cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxlifetime)}
http.SetCookie(w, &cookie)
} else {
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
我們用前面login操作來演示session的運用:
func login(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
r.ParseForm()
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("username"))
} else {
sess.Set("username", r.Form["username"])
http.Redirect(w, r, "/", 302)
}
}
SessionStart函數(shù)返回的是一個滿足Session接口的變量,那么我們該如何用他來對session數(shù)據(jù)進行操作呢?
上面的例子中的代碼session.Get("uid")
已經(jīng)展示了基本的讀取數(shù)據(jù)的操作,現(xiàn)在我們再來看一下詳細的操作:
func count(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
createtime := sess.Get("createtime")
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 360) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}
ct := sess.Get("countnum")
if ct == nil {
sess.Set("countnum", 1)
} else {
sess.Set("countnum", (ct.(int) + 1))
}
t, _ := template.ParseFiles("count.gtpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("countnum"))
}
通過上面的例子可以看到,Session的操作和操作key/value數(shù)據(jù)庫類似:Set、Get、Delete等操作
因為Session有過期的概念,所以我們定義了GC操作,當訪問過期時間滿足GC的觸發(fā)條件后將會引起GC,但是當我們進行了任意一個session操作,都會對Session實體進行更新,都會觸發(fā)對最后訪問時間的修改,這樣當GC的時候就不會誤刪除還在使用的Session實體。
我們知道,Web應用中有用戶退出這個操作,那么當用戶退出應用的時候,我們需要對該用戶的session數(shù)據(jù)進行銷毀操作,上面的代碼已經(jīng)演示了如何使用session重置操作,下面這個函數(shù)就是實現(xiàn)了這個功能:
//Destroy sessionid
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
return
} else {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionDestroy(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: manager.cookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
我們來看一下Session管理器如何來管理銷毀,只要我們在Main啟動的時候啟動:
func init() {
go globalSessions.GC()
}
func (manager *Manager) GC() {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionGC(manager.maxlifetime)
time.AfterFunc(time.Duration(manager.maxlifetime), func() { manager.GC() })
}
我們可以看到GC充分利用了time包中的定時器功能,當超時maxLifeTime
之后調(diào)用GC函數(shù),這樣就可以保證maxLifeTime
時間內(nèi)的session都是可用的,類似的方案也可以用于統(tǒng)計在線用戶數(shù)之類的。
至此 我們實現(xiàn)了一個用來在Web應用中全局管理Session的SessionManager,定義了用來提供Session存儲實現(xiàn)Provider的接口,下一小節(jié),我們將會通過接口定義來實現(xiàn)一些Provider,供大家參考學習。
更多建議: