Session

beego has a built-in session module. Currently, the backend engines supported by the session module include memory, cookie, file, mysql, redis, couchbase, memcache, postgres, and users can also implement their own engines according to the corresponding interfaces.

Web Session

Example

  1. web.BConfig.WebConfig.Session.SessionOn = true

Or in configuration file:

  1. sessionon = true

And then you can use session:

  1. func (this *MainController) Get() {
  2. v := this.GetSession("asta")
  3. if v == nil {
  4. this.SetSession("asta", int(1))
  5. this.Data["num"] = 0
  6. } else {
  7. this.SetSession("asta", v.(int)+1)
  8. this.Data["num"] = v.(int)
  9. }
  10. this.TplName = "index.tpl"
  11. }

session contains APIs:

  • SetSession(name string, value interface{})
  • GetSession(name string) interface{}
  • DelSession(name string)
  • SessionRegenerateID()
  • DestroySession()

Or you can get the entire session instance:

  1. sess:=this.StartSession()
  2. defer sess.SessionRelease()

sess contains APIs:

  • sess.Set()
  • sess.Get()
  • sess.Delete()
  • sess.SessionID()
  • sess.Flush()

But we still recommend you to use SetSession, GetSession, DelSession three methods to operate, to avoid the problem of not releasing resources in the process of their own operations.

Some parameters:

  • web.BConfig.WebConfig.Session.SessionOn: Set whether to open Session, the default is false, the corresponding parameter name of the configuration file: sessionon

  • web.BConfig.WebConfig.Session.SessionProvider: Set the engine of Session, the default is memory, currently there are file, mysql, redis, etc., the configuration file corresponds to the parameter name: sessionprovider.

  • web.BConfig.WebConfig.Session.SessionName: Set the name of cookies, Session is saved in the user’s browser cookies by default, the default name is beegosessionID, the corresponding parameter name of the configuration file is: sessionname.

  • web.BConfig.WebConfig.Session.SessionGCMaxLifetime: Set the Session expiration time, the default value is 3600 seconds, the corresponding parameter of the configuration file: sessiongcmaxlifetime.

  • web.BConfig.WebConfig.Session.SessionProviderConfig: Set the save path or address of the corresponding file, mysql, redis engines, the default value is empty, and the corresponding parameter of the configuration file: sessionproviderconfig.

  • web.BConfig.WebConfig.Session.SessionHashFunc: Default value is sha1, using sha1 encryption algorithm to produce sessionid

  • web.BConfig.WebConfig.Session.SessionCookieLifeTime: Set the expiration time for cookie, which is used to store data stored on the client.

When using a particular engine, you need to anonymously introduce the package corresponding to that engine to complete the initialization work:

  1. import _ "github.com/beego/beego/v2/server/web/session/mysql"

Engines

File

When SessionProvider is file SessionProviderConfig is the directory where the file is saved, as follows:

  1. web.BConfig.WebConfig.Session.SessionProvider="file"
  2. web.BConfig.WebConfig.Session.SessionProviderConfig = "./tmp"

MySQL

When SessionProvider is mysql, SessionProviderConfig is the address, using go-sql-driver, as follows:

  1. web.BConfig.WebConfig.Session.SessionProvider = "mysql"
  2. web.BConfig.WebConfig.Session.SessionProviderConfig = "username:password@protocol(address)/dbname?param=value"

It should be noted that when using mysql to store session information, you need to create a table in mysql beforehand, and the table creation statement is as follows:

  1. CREATE TABLE `session` (
  2. `session_key` char(64) NOT NULL,
  3. `session_data` blob,
  4. `session_expiry` int(11) unsigned NOT NULL,
  5. PRIMARY KEY (`session_key`)
  6. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Redis

When SessionProvider is redis , SessionProviderConfig is the address of redis, using redigo, as follows:

  1. web.BConfig.WebConfig.Session.SessionProvider = "redis"
  2. web.BConfig.WebConfig.Session.SessionProviderConfig = "127.0.0.1:6379"

memcache

When SessionProvider is memcache``, SessionProviderConfig is the address of memcache, using memcache, as follows:

  1. web.BConfig.WebConfig.Session.SessionProvider = "memcache"
  2. web.BConfig.WebConfig.Session.SessionProviderConfig = "127.0.0.1:7080"

Postgress

When SessionProvider is postgres , SessionProviderConfig is the address of postgres, using postgres, as follows:

  1. web.BConfig.WebConfig.Session.SessionProvider = "postgresql"
  2. web.BConfig.WebConfig.Session.SessionProviderConfig = "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full"

Couchbase

When SessionProvider is couchbase , SessionProviderConfig is the address of couchbase, using couchbase, as follows:

  1. web.BConfig.WebConfig.Session.SessionProvider = "couchbase"
  2. web.BConfig.WebConfig.Session.SessionProviderConfig = "http://bucketname:bucketpass@myserver:8091"

Notices

Because session uses gob to register stored objects, such as struct, if you use a non-memory engine, please register these structures in init of main.go yourself, otherwise it will cause an unresolvable error after application restart

Using Session Without Web Module

Import the module:

  1. import (
  2. "github.com/beego/beego/v2/server/web/session"
  3. )

Initiate the manager instance:

  1. var globalSessions *session.Manager

Next, initialize the data in your entry function:

  1. func init() {
  2. sessionConfig := &session.ManagerConfig{
  3. CookieName:"gosessionid",
  4. EnableSetCookie: true,
  5. Gclifetime:3600,
  6. Maxlifetime: 3600,
  7. Secure: false,
  8. CookieLifeTime: 3600,
  9. ProviderConfig: "./tmp",
  10. }
  11. globalSessions, _ = session.NewManager("memory",sessionConfig)
  12. go globalSessions.GC()
  13. }

Parameters 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 are the 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 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

Engines setting

We’ve already seen configuration of memory provider. Here is the configuration of the others:

  • mysql:

    All the parameters are the same as memory’s except the fourth parameter, 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. The Session module uses interfaces, so you can implement this interface to create your own provider easily.

  1. // Store contains all data for one session process with specific id.
  2. type Store interface {
  3. Set(ctx context.Context, key, value interface{}) error //set session value
  4. Get(ctx context.Context, key interface{}) interface{} //get session value
  5. Delete(ctx context.Context, key interface{}) error //delete session value
  6. SessionID(ctx context.Context) string //back current sessionID
  7. SessionRelease(ctx context.Context, w http.ResponseWriter) // release the resource & save data to provider & return the data
  8. Flush(ctx context.Context) error //delete all data
  9. }
  10. // Provider contains global session methods and saved SessionStores.
  11. // it can operate a SessionStore by its id.
  12. type Provider interface {
  13. SessionInit(ctx context.Context, gclifetime int64, config string) error
  14. SessionRead(ctx context.Context, sid string) (Store, error)
  15. SessionExist(ctx context.Context, sid string) (bool, error)
  16. SessionRegenerate(ctx context.Context, oldsid, sid string) (Store, error)
  17. SessionDestroy(ctx context.Context, sid string) error
  18. SessionAll(ctx context.Context) int // get all active session
  19. SessionGC(ctx context.Context)
  20. }

Finally, register your provider:

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