Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created May 8, 2019
Embed
What would you like to do?
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