Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active August 13, 2022 12:28
Show Gist options
  • Save alexedwards/0570e5a59677e278e13acb8ea53a3b30 to your computer and use it in GitHub Desktop.
Save alexedwards/0570e5a59677e278e13acb8ea53a3b30 to your computer and use it in GitHub Desktop.
SCS v2 Manual Load and Save
package main
import (
"io"
"net/http"
"github.com/alexedwards/scs/v2"
)
var session = scs.NewSession()
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/put", putMiddleware(putHandler))
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", mux)
}
func putMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, err := session.Load(r.Context(), r.Header.Get("X-Session"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
session.Put(ctx, "middlewareMessage", "Hello from putMiddleware!")
next.ServeHTTP(w, r.WithContext(ctx))
}
}
func putHandler(w http.ResponseWriter, r *http.Request) {
ctx, err := session.Load(r.Context(), r.Header.Get("X-Session"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
session.Put(ctx, "handlerMessage", "Hello from putHandler!")
token, expiry, err := session.Commit(ctx)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("X-Session", token)
w.Header().Set("X-Session-Expiry", expiry.Format(http.TimeFormat))
msg := session.GetString(ctx, "middlewareMessage")
io.WriteString(w, msg)
}
func getHandler(w http.ResponseWriter, r *http.Request) {
ctx, err := session.Load(r.Context(), r.Header.Get("X-Session"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
msg := session.GetString(ctx, "handlerMessage")
io.WriteString(w, msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment