Skip to content

SessionRecipes

rivo edited this page Nov 25, 2017 · 4 revisions

The main use of the sessions package is for browser sessions. Below you will find a bunch of code snippets that illustrate how the package can be used.

The snippets are typically placed at the beginning of a handler function for a HTTP(S) server, before any content is returned to the browser. These handler functions receive the two arguments response and request:

func handle(response http.ResponseWriter, request *http.Request) {
	// ...
}

We leave this part out because it's always the same and it will contain your own code, too.

Getting a User's Session

With all parameters set to their defaults, your code to get access to a user's session looks like this:

session, err := sessions.Start(response, request, false)
if err != nil {
  panic(err)
}
if session != nil {
  fmt.Println("We have a previously created session")
} else {
  fmt.Println("There was no session")
}

The session will be retrieved based on a session cookie. Depending on your security settings, that cookie may expire and will therefore be deleted or its value may change.

Creating a Session

Of course, if you've never created a session for a user, the code above will never return one. Many systems will create a session only when the user logs in, and you will find examples for this in the User Recipes section. But suppose we want a session for a user even before they log in, we simply provide true to the Start() function:

session, err := sessions.Start(response, request, true)
if err != nil {
  panic(err)
}
fmt.Println("We will always have a session")

If there was previously no session, it will be newly created and a cookie will be sent to the user's browser so the same session can be returned the next time we call Start().

Providing true will cause Start() to always return a session. You need to be aware that if the user's browser rejects your cookies, a new session will be created with every call. (Per default, these will all be cached and sent to the Persistence layer.)

Ending a Session

A session can be destroyed by calling Destroy():

if err := session.Destroy(response, request); err != nil {
  panic(err)
}

This will also set the browser cookie to "expired" so the browser will delete it. After this call, the session object should not be used anymore.

Storing and Retrieving Session Data

Sessions can hold data. Note that the data is attached to a session and not to a user. This is important because a user can be logged in with multiple sessions (e.g. on multiple devices). If you plan to synchronize data of a user across multiple sessions, data should be saved in a User object instead.

You can store any data in a session under a string key with Set() and retrieve it again with Get() (or GetAndDelete() which removes the item after it was returned):

func storeSomething(response http.ResponseWriter, request *http.Request) {
	session, _ := sessions.Start(response, request, true)
	if err := session.Set("city", "Berlin"); err != nil {
		panic(err)
	}
}

func retrieveSomething(response http.ResponseWriter, request *http.Request) {
	session, _ := sessions.Start(response, request, true)
	city := session.Get("city", nil)
	fmt.Fprint(response, city)
}

We omitted Start()'s error handling for clarity. But note that Set() returns an error as the call will write send the change to the Persistence layer which may fail.

Clone this wiki locally