session是一个独立的模块,即你能够那这个模块应用于其它Go程序中。mysql
session模块是用来存储客户端用户,session目前只支持cookie方式的请求,若是客户端不支持cookie,那么就没法使用该模块。git
session模块参考了database/sql的引擎写法,采用了一个接口,多个实现的方式。github
目前实现了memory、file、Redis和MySQL四种存储引擎。redis
经过下面的方式安装session:算法
go get github.com/astaxie/beego/session
首先你必须导入包:sql
import ( "github.com/astaxie/beego/session" )
而后你初始化一个全局变量用来存储session控制器:浏览器
var globalSessions *session.Manager
接着在你的入口函数中初始化数据:服务器
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函数的参数的函数以下所示:cookie
(1)引擎名字,能够是 memory、file、mysql 或 redis。session
(2)一个 JSON 字符串,传入 Manager 的配置信息
cookieName:客户端存储 cookie 的名字。
enableSetCookie,omitempty: 是否开启 SetCookie,omitempty 这个设置
gclifetime:触发 GC 的时间。
maxLifetime:服务器端存储的数据的过时时间
secure:是否开启 HTTPS,在 cookie 设置的时候有 cookie.Secure 设置。
sessionIDHashFunc:sessionID 生产的函数,默认是 sha1 算法。
sessionIDHashKey: hash 算法中的 key。
cookieLifeTime:客户端存储的 cookie 的时间,默认值是 0,即浏览器生命周期。
providerConfig: 配置信息,根据不一样的引擎设置不一样的配置信息,详细的配置请看下面的引擎设置
最后咱们的业务逻辑处理函数中能够这样调用:
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 有多个函数以下所示:
返回的 session 对象是一个 Interface,包含下面的方法
上面已经展现了 memory 的设置,接下来咱们看一下其余三种引擎的设置方式:
其余参数同样,只是第四个参数配置设置以下所示:
username:password@protocol(address)/dbname?param=value
配置文件信息以下所示,表示连接的地址,链接池,访问密码,没有保持为空:
注意:若使用redis等引擎做为session backend,请在使用前导入 < _ “github.com/astaxie/beego/session/redis” >
配置文件以下所示,表示须要保存的目录,默认是两级目录新建文件,例如 sessionID 是 xsnkjklkjjkh27hjh78908
,那么目录文件应该是 ./tmp/x/s/xsnkjklkjjkh27hjh78908
:
./tmp
在开发应用中,你可能须要实现本身的 session 引擎,beego 的这个 session 模块设计的时候就是采用了 interface,因此你能够根据接口实现任意的引擎,例如 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) }