Created
May 8, 2019 09:03
-
-
Save alexedwards/d6eca7136f98ec12ad606e774d3abad3 to your computer and use it in GitHub Desktop.
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" | |
"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