Choosing a session manager
There are a lot of security considerations when it comes to working with sessions, and proper implementation is not trivial. Unless you really need to roll your own implementation, it’s a good idea to use an existing, well-tested, third-party package here.
I recommend using either gorilla/sessions
, or alexedwards/scs
, depending on your project’s needs.
gorilla/sessions
is the most established and well-known session management package for Go. It has a simple and easy-to-use API, and let’s you store session data client-side (in signed and encrypted cookies) or server-side (in a database like MySQL, PostgreSQL or Redis).However — importantly — it doesn’t provide a mechanism to renew session IDs (which is necessary to reduce risks associated with session fixation attacks if you’re using one of the server-side session stores).
alexedwards/scs
lets you store session data server-side only. It supports automatic loading and saving of session data via middleware, has a nice interface for type-safe manipulation of data, and does allow renewal of session IDs. Likegorilla/sessions
, it also supports a variety of databases (including MySQL, PostgreSQL and Redis).
In summary, if you want to store session data client-side in a cookie then gorilla/sessions
is a good choice, but otherwise alexedwards/scs
is generally the better option due to the ability to renew session IDs.
For this project we’ve already got a MySQL database set up, so we’ll opt to use alexedwards/scs
and store the session data server-side in MySQL.
If you’re following along, make sure that you’re in your project directory and install the necessary packages like so:
$ go get github.com/alexedwards/scs/v2@v2 go: downloading github.com/alexedwards/scs/v2 v2.8.0 go get: added github.com/alexedwards/scs/v2 v2.8.0 $ go get github.com/alexedwards/scs/mysqlstore@latest go: downloading github.com/alexedwards/scs/mysqlstore v0.0.0-20240316133359-d7ab9d9831ec go get: added github.com/alexedwards/scs/mysqlstore v0.0.0-20240316133359-d7ab9d9831ec