diff options
author | Kamil Kisiel <kamil@kamilkisiel.net> | 2015-08-09 20:23:05 +0300 |
---|---|---|
committer | Kamil Kisiel <kamil@kamilkisiel.net> | 2015-08-09 20:23:05 +0300 |
commit | b49790bad8a5f6601c6feef28facd4f8e1e43ed1 (patch) | |
tree | 08e8f86cad6a9ccdc4286c3df462506523196d25 | |
parent | e727cdeb0ad3561b76d753ceeb50d900baf6344e (diff) | |
parent | 67c3cbe3ac0f28c1688322d3942e68bf84061ac4 (diff) |
Merge pull request #51 from elithrar/assert-from-session
Added example of retrieving from a session.
-rw-r--r-- | doc.go | 34 |
1 files changed, 32 insertions, 2 deletions
@@ -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 |