Created
May 3, 2017 16:37
-
-
Save vogxn/84b94d90476f91375689e337335d2360 to your computer and use it in GitHub Desktop.
How to use slices of custom type in sessions?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/gob" | |
"fmt" | |
"github.com/gorilla/mux" | |
"github.com/gorilla/sessions" | |
"net/http" | |
) | |
type Person struct { | |
Name string | |
Age string | |
} | |
var store = sessions.NewCookieStore([]byte("foobar")) | |
var persons []Person | |
func main() { | |
r := mux.NewRouter() | |
sub := r.Methods("GET", "POST").Subrouter() | |
sub.HandleFunc("/person/{name}/{age:[0-9]+}", PostHandler) | |
sub.HandleFunc("/person/", GetHandler) | |
srv := &http.Server{ | |
Handler: r, | |
Addr: "127.0.0.1:8080", | |
} | |
srv.ListenAndServe() | |
} | |
func init() { | |
gob.Register(&Person{}) | |
} | |
func PostHandler(w http.ResponseWriter, r *http.Request) { | |
session, err := store.Get(r, "spamspam") | |
if err != nil { | |
fmt.Fprintf(w, "invalid session: %+v\n", err) | |
} | |
vars := mux.Vars(r) | |
persons = append(persons, Person{Name: vars["name"], Age: vars["age"]}) | |
fmt.Fprintf(w, "persons: %+v\n", persons) | |
session.Values["persons"] = persons | |
session.Save(r, w) | |
} | |
func GetHandler(w http.ResponseWriter, r *http.Request) { | |
session, err := store.Get(r, "spamspam") | |
if err != nil { | |
fmt.Fprintf(w, "invalid session: %+v\n", err) | |
} | |
val := session.Values["persons"] | |
// What type is the session value `val`? | |
if persons, ok := val.([]Person); ok { | |
for _, person := range persons { | |
fmt.Fprintln(w, person) | |
} | |
} else { | |
fmt.Fprintf(w, "invalid type detected: %+v\n", ok) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment