scs

repository·master·Indexed 25 days ago

https://github.com/alexedwards/scs

A high-performance HTTP session management library for Go that uses middleware to automate the loading and saving of session data. It supports multiple session stores including badgerstore, boltstore, bunstore, buntdbstore, cockroachdbstore, and consulstore.

Tokens
28.9K
Snippets
77
Records
163
Agent score
83%

What's inside scs

  1. Overview of SCS: HTTP Session Management for Go

    master

    SCS is a session management library for Go designed to be efficient, fast, and memory-light. It provides automatic loading and saving of session data via middleware and supports a wide variety of server-side session stores (including PostgreSQL, MySQL, Redis, and more).

    Key capabilities include:

    • Multiple sessions per request.
    • 'Flash' messages.
    • Session token regeneration.
    • Idle and absolute session timeouts.
    • 'Remember me' functionality.
    • Flexible token communication (via HTTP headers or request/response bodies).
  2. Use memstore for in-memory session storage

    master

    memstore is an in-memory session store for SCS. It is the default store used if no other store is specified.

    Warning: Because it uses in-memory storage, all session data is lost when the application stops or restarts. Use it for prototyping, testing, or applications where performance is prioritized over data persistence.

    package main
    
    import (
    	"io"
    	"net/http"
    
    	"github.com/alexedwards/scs/v2"
    	"github.com/alexedwards/scs/v2/memstore"
    )
    
    var sessionManager *scs.SessionManager
    
    func main() {
    	// Initialize a new session manager and configure it to use memstore as the session store.
    	sessionManager = scs.New()
    	sessionManager.Store = memstore.New()
    
    	mux := http.NewServeMux()
    	mux.HandleFunc("/put", putHandler)
    	mux.HandleFunc("/get", getHandler)
    
    	http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux))
    }
    
    func putHandler(w http.ResponseWriter, r *http.Request) {
    	sessionManager.Put(r.Context(), "message", "Hello from a session!")
    }
    
    func getHandler(w http.ResponseWriter, r *http.Request) {
    	msg := sessionManager.GetString(r.Context(), "message")
    	io.WriteString(w, msg)
    }
  3. Setup consulstore for SCS

    master

    To use Consul as a session store for SCS, establish a connection using the HashiCorp Consul API client and pass that client to consulstore.New(). This client is then assigned to the Store field of an scs.SessionManager.

    // Establish connection to Consul.
    cli, err := api.NewClient(api.DefaultConfig())
    if err != nil {
    	log.Fatal(err)
    }
    
    // Initialize a new session manager and configure it to use consulstore as the session store.
    sessionManager = scs.New()
    sessionManager.Store = consulstore.New(cli)
  4. Setup buntdbstore for SCS

    master

    To use BuntDB as a session store for SCS, you must first install and open a BuntDB database instance. Pass the opened database instance to buntdbstore.New() and assign the resulting store to the Store field of your scs.SessionManager.

    // Open a BuntDB database.
    db, err := buntdb.Open("tmp/buntdb.db")
    if err != nil {
    	log.Fatal(err)
    }
    defer db.Close()
    
    // Initialize a new session manager and configure it to use buntdbstore as the session store.
    sessionManager = scs.New()
    sessionManager.Store = buntdbstore.New(db)
  5. Set up CockroachDB for cockroachdbstore

    master

    To use cockroachdbstore, you must have a CockroachDB database with a sessions table. The table requires a specific schema to handle session tokens, binary data, and expiry timestamps. Additionally, the database user must have SELECT, INSERT, UPDATE, and DELETE permissions on this table.

    CREATE TABLE sessions (
    	token TEXT PRIMARY KEY,
    	data BYTEA NOT NULL,
    	expiry TIMESTAMPTZ NOT NULL
    );
    
    CREATE INDEX sessions_expiry_idx ON sessions (expiry);
  6. Set up the SQLite3 database schema for sqlite3store

    master

    To use sqlite3store, you must have a SQLite3 database containing a sessions table with the following schema. It is also recommended to create an index on the expiry column to optimize cleanup operations.

    CREATE TABLE sessions (
    	token TEXT PRIMARY KEY,
    	data BLOB NOT NULL,
    	expiry REAL NOT NULL
    );
    
    CREATE INDEX sessions_expiry_idx ON sessions(expiry);
  7. Setup boltstore for SCS

    master

    To use boltstore as a session store for SCS, you must first open a Bolt database using the bbolt package, then pass that database instance to boltstore.New().

    // Open a Bolt database.
    db, err := bbolt.Open("/tmp/bolt.db", 0600, nil)
    if err != nil {
    	log.Fatal(err)
    }
    defer db.Close()
    
    // Initialize a new session manager and configure it to use boltstore.
    sessionManager = scs.New()
    sessionManager.Store = boltstore.New(db)
  8. Set up badgerstore for SCS session management

    master

    To use badgerstore as a session store for SCS, you must first install and open a Badger database. Once the database is open, pass the database instance to badgerstore.New() and assign the resulting store to the Store field of an scs.SessionManager.

    // Open a Badger database.
    db, err := badger.Open(badger.DefaultOptions("tmp/badger"))
    if err != nil {
    	log.Fatal(err)
    }
    defer db.Close()
    
    // Initialize a new session manager and configure it to use badgerstore as the session store.
    sessionManager = scs.New()
    sessionManager.Store = badgerstore.New(db)
  9. Setup redisstore for SCS

    master

    To use Redis as a session store for SCS, you must first establish a connection pool using the redigo library. Pass this pool to redisstore.New() to create the session store, which you then assign to the Store field of an scs.SessionManager.

    // Establish connection pool to Redis.
    pool := &redis.Pool{
    	MaxIdle: 10,
    	Dial: func() (redis.Conn, error) {
    		return redis.Dial("tcp", "host:6379")
    	},
    }
    
    // Initialize a new session manager and configure it to use redisstore as the session store.
    sessionManager = scs.New()
    sessionManager.Store = redisstore.New(pool)
  10. Set up PostgreSQL for postgresstore

    master

    To use postgresstore, you must have a PostgreSQL database with a sessions table. The table requires a specific schema to store session tokens, data, and expiry timestamps. Ensure your application's database user has SELECT, INSERT, UPDATE, and DELETE permissions on this table.

    Run the following SQL to create the required table and index:

    CREATE TABLE sessions (
    	token TEXT PRIMARY KEY,
    	data BYTEA NOT NULL,
    	expiry TIMESTAMPTZ NOT NULL
    );
    
    CREATE INDEX sessions_expiry_idx ON sessions (expiry);
  11. Set up the MySQL table for mysqlstore

    master

    To use mysqlstore, you must have a MySQL database with a sessions table. Ensure your database user has SELECT, INSERT, UPDATE, and DELETE permissions on this table.

    CREATE TABLE sessions (
    	token CHAR(43) COLLATE utf8mb4_bin PRIMARY KEY,
    	data BLOB NOT NULL,
    	expiry TIMESTAMP(6) NOT NULL
    );
    
    CREATE INDEX sessions_expiry_idx ON sessions (expiry);
  12. Install SCS v2

    master

    Install the SCS package using Go modules. This package requires Go 1.12 or newer.

    If you are using the traditional GOPATH mechanism instead of modules, import github.com/alexedwards/scs without the v2 suffix.

    go get github.com/alexedwards/scs/v2