Using MySQL as session provider in Beego

Copyright Beego.me

Beego is a MVC framework for the Go programming language. For someone like me who hates writing boilerplate code, Beego is a life saver.

The Issue

This post is specifically about using MySQL as the session storage instead of the default memory option. The reason you should upgrade to using MySQL as the session provider is because the memory option fails if your application is reset or if the garbage collector clears your session memory.

The reason I am inclined to write this post is because the official documentation is outdated and I wasted months trying to figure out what the issue was while using MySQL as the provider. After tracing through the source I was able to find out the line of the code that was the problem.

The Solution

Follow these instructions and you should have your code running in no time.


Make sure the DB table is created. Run this script if it is not.


CREATE TABLE `session` (
`session_key` char(64) NOT NULL,
`session_data` blob,
`session_expiry` int(11) unsigned NOT NULL,
PRIMARY KEY (`session_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Then in your main.go function import the following


import(
_ “github.com/astaxie/beego/session/mysql”
“github.com/astaxie/beego/session”
)

Change your app.conf settings to enable sessions and to use MySQL as the provider.

SessionOn = true
SessionProvider = mysql
SessionProviderConfig = username:password@tcp(127.0.0.1:3306)/dbname

Note that the documentation says to use

SessionSavePath = username:password@tcp(127.0.0.1:3306)/dbname

which I believe is incorrect. It has to be SessionProviderConfig.

After that, you should be able to access your session variables using the existing methods.

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

I hope this solution works for you. Happy Coding!