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:

  1. go get github.com/astaxie/beego/session

Basic Usage:

Import package first:

  1. import (
  2. "github.com/astaxie/beego/session"
  3. )

Then initialize a global variable as the session manager:

  1. var globalSessions *session.Manager

Then initialize data in your main function:

  1. func init() {
  2. globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "sessionIDHashFunc": "sha1", "sessionIDHashKey": "", "cookieLifeTime": 3600, "providerConfig": ""}`)
  3. go globalSessions.GC()
  4. }

Paramters of NewManager:

  1. Saving provider name: memory, file, mysql, redis
  2. A JSON string that contains the config information.
    1. cookieName: Cookie name of session id saved on the client
    2. enableSetCookie, omitempty: Whether to enable SetCookie, omitempty
    3. gclifetime: The interval of GC.
    4. maxLifetime: Expiration time of data saved on the server
    5. secure: Enable https or not. There is cookie.Secure while configure cookie.
    6. sessionIDHashFunc: SessionID generator function. sha1 by default.
    7. sessionIDHashKey: Hash key.
    8. cookieLifeTime: Cookie expiration time on the client. 0 by default, which means life time of browser.
    9. providerConfig: Provider-specific config. See below for more information.

Then we can use session in our code:

  1. func login(w http.ResponseWriter, r *http.Request) {
  2. sess, _ := globalSessions.SessionStart(w, r)
  3. defer sess.SessionRelease(w)
  4. username := sess.Get("username")
  5. if r.Method == "GET" {
  6. t, _ := template.ParseFiles("login.gtpl")
  7. t.Execute(w, nil)
  8. } else {
  9. sess.Set("username", r.Form["username"])
  10. }
  11. }

Here is methods of globalSessions:

  • SessionStart Return session object based on current request.
  • SessionDestroy Destroy current session object.
  • SessionRegenerateId Regenerate a new sessionID.
  • GetActiveSession Get active session user.
  • SetHashFunc Set sessionID generator function.
  • SetSecure Enable Secure of cookie or not.

The returned session object is a Interface. Here are the methods:

  • Set(key, value interface{}) error
  • Get(key interface{}) interface{}
  • Delete(key interface{}) error
  • SessionID() string
  • SessionRelease()
  • 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.:

    1. username:password@protocol(address)/dbname?param=value

    For details see the go-sql-driver/mysql documentation.

  • redis:

    Connection config: address,pool,password

    1. 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 xsnkjklkjjkh27hjh78908 the file will be saved as ./tmp/x/s/xsnkjklkjjkh27hjh78908

    1. ./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.

  1. // SessionStore contains all data for one session process with specific id.
  2. type SessionStore interface {
  3. Set(key, value interface{}) error // Set session value
  4. Get(key interface{}) interface{} // Get session value
  5. Delete(key interface{}) error // Delete session value
  6. SessionID() string // Get current session ID
  7. SessionRelease(w http.ResponseWriter) // Release the resource & save data to provider & return the data
  8. Flush() error // Delete all data
  9. }
  10. type Provider interface {
  11. SessionInit(maxlifetime int64, savePath string) error
  12. SessionRead(sid string) (SessionStore, error)
  13. SessionExist(sid string) bool
  14. SessionRegenerate(oldsid, sid string) (SessionStore, error)
  15. SessionDestroy(sid string) error
  16. SessionAll() int // Get all active session
  17. SessionGC()
  18. }

At last, register your provider:

  1. func init() {
  2. // ownadapter is an instance of session.Provider
  3. session.Register("own", ownadapter)
  4. }