2016-07-21 20:34:24 +00:00
|
|
|
package examples
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2018-11-23 20:10:42 +00:00
|
|
|
"gitto.work/shortcut/pgstorex"
|
2016-07-21 20:34:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ExampleHandler is an example that displays the usage of PGStore.
|
|
|
|
func ExampleHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Fetch new store.
|
2018-11-23 20:10:42 +00:00
|
|
|
store, err := pgstorex.NewPGStore("postgres://user:password@127.0.0.1:5432/database?sslmode=verify-full", []byte("secret-key"))
|
2016-07-21 20:34:24 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf(err.Error())
|
|
|
|
}
|
|
|
|
defer store.Close()
|
|
|
|
|
|
|
|
// Run a background goroutine to clean up expired sessions from the database.
|
|
|
|
defer store.StopCleanup(store.Cleanup(time.Minute * 5))
|
|
|
|
|
|
|
|
// Get a session.
|
|
|
|
session, err := store.Get(r, "session-key")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf(err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add a value.
|
|
|
|
session.Values["foo"] = "bar"
|
|
|
|
|
|
|
|
// Save.
|
|
|
|
if err = session.Save(r, w); err != nil {
|
|
|
|
log.Fatalf("Error saving session: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete session.
|
|
|
|
session.Options.MaxAge = -1
|
|
|
|
if err = session.Save(r, w); err != nil {
|
|
|
|
log.Fatalf("Error saving session: %v", err)
|
|
|
|
}
|
|
|
|
}
|