aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--doc.go34
1 files 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