Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
Find a file
2023-12-06 12:47:28 +08:00
.gitignore update 2023-11-29 14:54:10 +08:00
.travis.yml Update .travis.yml 2015-08-19 22:17:45 -07:00
doc.go update 2017-04-20 14:44:54 +08:00
lex.go update 2017-04-21 23:53:14 +08:00
LICENSE Initial files. 2012-10-03 01:49:24 -03:00
README.md Add https://github.com/wader/gormstore 2016-01-07 00:28:49 +01:00
sessions.go update 2022-01-20 16:19:49 +08:00
store.go update 2023-12-06 12:45:23 +08:00
utils.go update 2023-12-06 12:47:28 +08:00

sessions

GoDoc Build Status

gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.

The key features are:

  • Simple API: use it as an easy way to set signed (and optionally encrypted) cookies.
  • Built-in backends to store sessions in cookies or the filesystem.
  • Flash messages: session values that last until read.
  • Convenient way to switch session persistency (aka "remember me") and set other attributes.
  • Mechanism to rotate authentication and encryption keys.
  • Multiple sessions per request, even using different backends.
  • Interfaces and infrastructure for custom session backends: sessions from different stores can be retrieved and batch-saved using a common API.

Let's start with an example that shows the sessions API in a nutshell:

	import (
		"net/http"
		"github.com/gorilla/sessions"
	)

	var store = sessions.NewCookieStore([]byte("something-very-secret"))

	func MyHandler(w http.ResponseWriter, r *http.Request) {
		// Get a session. We're ignoring the error resulted from decoding an
		// existing session: Get() always returns a session, even if empty.
		session, _ := store.Get(r, "session-name")
		// Set some session values.
		session.Values["foo"] = "bar"
		session.Values[42] = 43
		// Save it before we write to the response/return from the handler.
		session.Save(r, w)
	}

First we initialize a session store calling NewCookieStore() and passing a secret key used to authenticate the session. Inside the handler, we call store.Get() to retrieve an existing session or a new one. Then we set some session values in session.Values, which is a map[interface{}]interface{}. And finally we call session.Save() to save the session in the response.

Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:

More examples are available on the Gorilla website.

Store Implementations

Other implementations of the sessions.Store interface:

License

BSD licensed. See the LICENSE file for details.