beego的Session模塊

2023-11-21 10:45 更新

特別注意

這個文檔是 session 獨立模塊,即你單獨拿這個模塊應用于其他應用中,如果你想在 beego 中使用 session,請查看文檔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

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ù)如下所示

  1. 引擎名字,可以是 memory、file、mysql 或 redis。
  2. 一個 JSON 字符串,傳入 Manager 的配置信息cookieName: 客戶端存儲 cookie 的名字。enableSetCookie,omitempty: 是否開啟 SetCookie,omitempty 這個設置gclifetime: 觸發(fā) GC 的時間。maxLifetime: 服務器端存儲的數(shù)據(jù)的過期時間secure: 是否開啟 HTTPS,在 cookie 設置的時候有 cookie.Secure 設置。sessionIDHashFunc: sessionID 生產(chǎn)的函數(shù),默認是 sha1 算法。sessionIDHashKey: hash 算法中的 key。cookieLifeTime: 客戶端存儲的 cookie 的時間,默認值是 0,即瀏覽器生命周期。providerConfig: 配置信息,根據(jù)不同的引擎設置不同的配置信息,詳細的配置請看下面的引擎設置

最后我們的業(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ù)如下所示:

  • SessionStart 根據(jù)當前請求返回 session 對象
  • SessionDestroy 銷毀當前 session 對象
  • SessionRegenerateId 重新生成 sessionID
  • GetActiveSession 獲取當前活躍的 session 用戶
  • SetHashFunc 設置 sessionID 生成的函數(shù)
  • SetSecure 設置是否開啟 cookie 的 Secure 設置

返回的 session 對象是一個 Interface,包含下面的方法

  • Set(key, value interface{}) error
  • Get(key interface{}) interface{}
  • Delete(key interface{}) error
  • SessionID() string
  • SessionRelease()
  • Flush() error

引擎設置

上面已經(jīng)展示了 memory 的設置,接下來我們看一下其他三種引擎的設置方式:

  • mysql其他參數(shù)一樣,只是第四個參數(shù)配置設置如下所示,詳細的配置請參考 mysql: username:password@protocol(address)/dbname?param=value
  • redis配置文件信息如下所示,表示鏈接的地址,連接池,訪問密碼,沒有保持為空:注意:若使用redis等引擎作為session backend,請在使用前導入 < _ "github.com/astaxie/beego/session/redis" > 否則會在運行時發(fā)生錯誤,使用其他引擎時也是同理。 127.0.0.1:6379,100,astaxie
  • file配置文件如下所示,表示需要保存的目錄,默認是兩級目錄新建文件,例如 sessionID 是 xsnkjklkjjkh27hjh78908,那么目錄文件應該是 ./tmp/x/s/xsnkjklkjjkh27hjh78908: ./tmp

如何創(chuàng)建自己的引擎

在開發(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)
}


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號