buntdbstore

package module
v0.0.0-...-7e11d57 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2024 License: MIT Imports: 2 Imported by: 0

README

buntdbstore

A BuntDB based session store for SCS.

Setup

You should follow the instructions to install and open a database, and pass the database to buntdbstore.New() to establish the session store.

Example

package main

import (
	"io"
	"net/http"

	"github.com/alexedwards/scs/v2"
	"github.com/alexedwards/scs/buntdbstore"
	"github.com/tidwall/buntdb"
)

var sessionManager *scs.SessionManager

func main() {
	// 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)

	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)
}

Expired Session Cleanup

BuntDB will automatically remove expired session keys.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BuntDBStore

type BuntDBStore struct {
	// contains filtered or unexported fields
}

BuntDBStore represents the session store.

func New

func New(db *buntdb.DB) *BuntDBStore

New returns a new BuntDBStore instance. The db parameter should be a pointer to a buntdb store instance.

func (*BuntDBStore) All

func (bs *BuntDBStore) All() (map[string][]byte, error)

All returns a map containing the token and data for all active (i.e. not expired) sessions in the BuntDBStore instance.

func (*BuntDBStore) Commit

func (bs *BuntDBStore) Commit(token string, b []byte, expiry time.Time) error

Commit adds a session token and data to the BuntDBStore instance with the given expiry time. If the session token already exists then the data and expiry time are updated.

func (*BuntDBStore) Delete

func (bs *BuntDBStore) Delete(token string) error

Delete removes a session token and corresponding data from the BuntDBStore instance.

func (*BuntDBStore) Find

func (bs *BuntDBStore) Find(token string) (b []byte, exists bool, err error)

Find returns the data for a given session token from the BuntDBStore instance. If the session token is not found or is expired, the returned exists flag will be set to false.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL