Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active August 13, 2022 12:59
Show Gist options
  • Save alexedwards/22535f758356bfaf96038fffad154824 to your computer and use it in GitHub Desktop.
Save alexedwards/22535f758356bfaf96038fffad154824 to your computer and use it in GitHub Desktop.
SCS v2 Multiple Sessions
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
"github.com/alexedwards/scs/v2"
"github.com/alexedwards/scs/postgresstore"
_ "github.com/lib/pq"
)
var sessionOne, sessionTwo *scs.Session
func main() {
db, err := sql.Open("postgres", "postgres://user:pass@localhost/db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Initialize and configure a session manager with long-lived sessions using
// the PostgreSQL session store.
sessionOne = scs.NewSession()
sessionOne.Store = postgresstore.New(db)
sessionOne.Lifetime = 72 * time.Hour
sessionOne.Cookie.Name = "sessionOne" // Important: This must be unique; two sessions should not have the same cookie name.
// Initialize and configure another session manager with short-lived sessions
// using the default in-memory session store.
sessionTwo = scs.NewSession()
sessionTwo.Lifetime = 10 * time.Minute
sessionTwo.Cookie.Name = "sessionTwo" // Important: This must be unique; two sessions should not have the same cookie name.
mux := http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
http.ListenAndServe(":4000", sessionOne.LoadAndSave(sessionTwo.LoadAndSave(mux)))
}
func putHandler(w http.ResponseWriter, r *http.Request) {
sessionOne.Put(r.Context(), "messageOne", "Hello from sessionOne")
sessionTwo.Put(r.Context(), "messageTwo", "Hello from sessionTwo")
}
func getHandler(w http.ResponseWriter, r *http.Request) {
msg := sessionOne.GetString(r.Context(), "messageOne")
fmt.Fprintln(w, msg)
msg = sessionTwo.GetString(r.Context(), "messageTwo")
fmt.Fprintln(w, msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment