From 67c3cbe3ac0f28c1688322d3942e68bf84061ac4 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sat, 8 Aug 2015 20:04:39 +0800 Subject: [PATCH] Added example of retrieving from a session. --- doc.go | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/doc.go b/doc.go index 7c09f8b..c5a3274 100644 --- a/doc.go +++ b/doc.go @@ -31,7 +31,12 @@ Let's start with an example that shows the sessions API in a nutshell: 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") + session, err := store.Get(r, "session-name") + if err != nil { + http.Error(w, err.Error(), 500) + return + } + // Set some session values. session.Values["foo"] = "bar" session.Values[42] = 43 @@ -66,7 +71,12 @@ flashes, call session.Flashes(). Here is an example: func MyHandler(w http.ResponseWriter, r *http.Request) { // Get a session. - session, _ := store.Get(r, "session-name") + session, err := store.Get(r, "session-name") + if err != nil { + http.Error(w, err.Error(), 500) + return + } + // Get the previously flashes, if any. if flashes := session.Flashes(); len(flashes) > 0 { // Just print the flash values. @@ -112,6 +122,26 @@ above we've passed it a pointer to a struct and a pointer to a custom type representing a map[string]interface. This will then allow us to serialise/deserialise values of those types to and from our sessions. +Note that because session values are stored in a map[string]interface{}, there's +a need to type-assert data when retrieving it. We'll use the Person struct we registered above: + + func MyHandler(w http.ResponseWriter, r *http.Request) { + session, err := store.Get(r, "session-name") + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + // Retrieve our struct and type-assert it + val := session.Values["person"] + var person &Person{} + if person, ok := val.(*Person); !ok { + // Handle the case that it's not an expected type + } + + // Now we can use our person object + } + By default, session cookies last for a month. This is probably too long for some cases, but it is easy to change this and other attributes during runtime. Sessions can be configured individually or the store can be