diff options
Diffstat (limited to 'doc.go')
-rw-r--r-- | doc.go | 36 |
1 files changed, 33 insertions, 3 deletions
@@ -31,11 +31,16 @@ 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 - // Save it. + // Save it before we write to the response/return from the handler. session.Save(r, w) } @@ -69,7 +74,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 { // Use the flash values. @@ -113,6 +123,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 |