Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created May 8, 2019 09:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexedwards/d6eca7136f98ec12ad606e774d3abad3 to your computer and use it in GitHub Desktop.
Save alexedwards/d6eca7136f98ec12ad606e774d3abad3 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/gob"
"fmt"
"net/http"
"github.com/alexedwards/scs/v2"
)
// Note that the fields on the custom type are all exported.
type User struct {
Name string
Age int
}
var session *scs.Session
// Register the custom type with the encoding/gob package.
func init() {
gob.Register(User{})
}
func main() {
session = scs.NewSession()
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", session.LoadAndSave(mux))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
user := &User{"Alice", 42}
session.Put(r.Context(), "user", user)
}
func getHandler(w http.ResponseWriter, r *http.Request) {
user, ok := session.Get(r.Context(), "user").(User)
if !ok {
http.Error(w, "could not convert value to User", 500)
}
fmt.Fprintf(w, "%s: %d", user.Name, user.Age)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment