name: Session Module
sort: 1
Introduction to Session Module
The session module is used to store user data between different requests. It only supports saving the session id into a cookie, so if the client doesn’t support cookies, it won’t work.
It is inspired by database/sql, which means: one interface, multiple implementations. By default it supports four saving providers: memory, file, redis and mysql.
Install session module:
go get github.com/astaxie/beego/session
Basic Usage:
Import package first:
import ("github.com/astaxie/beego/session")
Then initialize a global variable as the session manager:
var globalSessions *session.Manager
Then initialize data in your main function:
func init() {globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "sessionIDHashFunc": "sha1", "sessionIDHashKey": "", "cookieLifeTime": 3600, "providerConfig": ""}`)go globalSessions.GC()}
Paramters of NewManager:
- Saving provider name: memory, file, mysql, redis
- A JSON string that contains the config information.
- cookieName: Cookie name of session id saved on the client
- enableSetCookie, omitempty: Whether to enable SetCookie, omitempty
- gclifetime: The interval of GC.
- maxLifetime: Expiration time of data saved on the server
- secure: Enable https or not. There is
cookie.Securewhile configure cookie. - sessionIDHashFunc: SessionID generator function.
sha1by default. - sessionIDHashKey: Hash key.
- cookieLifeTime: Cookie expiration time on the client. 0 by default, which means life time of browser.
- providerConfig: Provider-specific config. See below for more information.
Then we can use session in our code:
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"])}}
Here is methods of globalSessions:
SessionStartReturn session object based on current request.SessionDestroyDestroy current session object.SessionRegenerateIdRegenerate a new sessionID.GetActiveSessionGet active session user.SetHashFuncSet sessionID generator function.SetSecureEnable Secure of cookie or not.
The returned session object is a Interface. Here are the methods:
Set(key, value interface{}) errorGet(key interface{}) interface{}Delete(key interface{}) errorSessionID() stringSessionRelease()Flush() error
Saving Provider Config
We’ve already seen configuration of memory provider. Here is the config of the others:
mysql:All the parameters are the same as memory’s except the fourth param, e.g.:
username:password@protocol(address)/dbname?param=value
For details see the go-sql-driver/mysql documentation.
redis:Connection config: address,pool,password
127.0.0.1:6379,100,astaxie
file:The session save path. Create new files in two levels by default. E.g.: if sessionID is
xsnkjklkjjkh27hjh78908the file will be saved as./tmp/x/s/xsnkjklkjjkh27hjh78908./tmp
Creating a new provider
Sometimes you need to create your own session provider. Session module uses interfaces, so you can implement this interface to create your own provider easily.
// SessionStore contains all data for one session process with specific id.type SessionStore interface {Set(key, value interface{}) error // Set session valueGet(key interface{}) interface{} // Get session valueDelete(key interface{}) error // Delete session valueSessionID() string // Get current session IDSessionRelease(w http.ResponseWriter) // Release the resource & save data to provider & return the dataFlush() error // Delete all data}type Provider interface {SessionInit(maxlifetime int64, savePath string) errorSessionRead(sid string) (SessionStore, error)SessionExist(sid string) boolSessionRegenerate(oldsid, sid string) (SessionStore, error)SessionDestroy(sid string) errorSessionAll() int // Get all active sessionSessionGC()}
At last, register your provider:
func init() {// ownadapter is an instance of session.Providersession.Register("own", ownadapter)}
