Session Management for QOR
It wrapped other libs like SCS, Gorilla Session into a common interface, which will be used for QOR libs and your application.
import (
"github.com/gorilla/sessions""github.com/qor/session/gorilla"// "github.com/alexedwards/scs/engine/memstore"
)
varSessionManager=session.ManagerInterfacefuncmain() {
// Use gorilla session as the backendengine:=sessions.NewCookieStore([]byte("something-very-secret"))
SessionManager=gorilla.New("_session", engine)
// Use SCS as the backend// engine := memstore.New(0)// SessionManager := scs.New(engine)mux:=http.NewServeMux()
mux.HandleFunc("/put", putHandler)
mux.HandleFunc("/get", getHandler)
// Your routes// Wrap your application's handlers or router with session manager's middlewarehttp.ListenAndServe(":7000", manager.Middleware(mux))
}
funcputHandler(w http.ResponseWriter, req*http.Request) {
// Store a key and associated value into session dataSessionManager.Add(w, req, "key", "value")
}
funcgetHandler(w http.ResponseWriter, req*http.Request) {
// Get saved session data with keyvalue:=SessionManager.Get(req, "key")
io.WriteString(w, value)
}typeManagerInterfaceinterface {
// Add value to session data, if value is not string, will marshal it into JSON encoding and save it into session data.Add(w http.ResponseWriter, req*http.Request, keystring, valueinterface{}) error// Get value from session dataGet(req*http.Request, keystring) string// Pop value from session dataPop(w http.ResponseWriter, req*http.Request, keystring) string// Flash add flash message to session dataFlash(w http.ResponseWriter, req*http.Request, messageMessage) error// Flashes returns a slice of flash messages from session dataFlashes(w http.ResponseWriter, req*http.Request) []Message// Load get value from session data and unmarshal it into resultLoad(req*http.Request, keystring, resultinterface{}) error// PopLoad pop value from session data and unmarshal it into resultPopLoad(w http.ResponseWriter, req*http.Request, keystring, resultinterface{}) error// Middleware returns a new session manager middleware instance.Middleware(http.Handler) http.Handler
}We have created a default session manager in package github.com/qor/session/manager, which is used in some QOR libs like QOR Admin, QOR Auth by default to manage session, flash messages.
It is defined like below:
varSessionManager session.ManagerInterface=gorilla.New("_session", sessions.NewCookieStore([]byte("secret")))You should change it to your own session storage or use your own secret code.
import (
"github.com/qor/session/manager"
)
funcmain() {
// Overwrite session managerengine:=sessions.NewCookieStore([]byte("your-own-secret-code"))
manager.SessionManager=gorilla.New("_gorilla_session", engine)
}Released under the MIT License.