sessionstore

package module
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2024 License: MIT Imports: 16 Imported by: 1

README

Session Store Open in Gitpod

Tests Status Go Report Card PkgGoDev

Stores session to a database table.

Installation

go get -u github.com/gouniverse/sessionstore

Setup

sessionStore = sessionstore.NewStore(sessionstore.NewStoreOptions{
	DB:                 databaseInstance,
	SessionTableName:   "my_session",
	TimeoutSeconds:     3600, // 1 hour
	AutomigrateEnabled: true,
	DebugEnabled:       false,
})

go sessionStore.ExpireSessionGoroutine()

Methods

  • AutoMigrate() error - automigrate (creates) the session table
  • DriverName(db *sql.DB) string - finds the driver name from database
  • EnableDebug(debug bool) - enables / disables the debug option
  • ExpireSessionGoroutine() error - deletes the expired session keys
  • Delete(sessionKey string, options SessionOptions) (bool, error) - Delete deletes a session
  • Extend(sessionKey string, seconds int64, options SessionOptions) error - Extends a session
  • FindByKey(sessionKey string, options SessionOptions) (*Session, error) - FindByKey finds a session by key
  • Get(sessionKey string, valueDefault string, options SessionOptions) (string, error) - Gets the session value as a string
  • GetAny(key string, valueDefault any, options SessionOptions) (any, error) - attempts to parse the value as interface, use with SetAny
  • GetMap(key string, valueDefault map[string]any, options SessionOptions) (map[string]any, error) - attempts to parse the value as map[string]any, use with SetMap
  • Has(sessionKey string, options SessionOptions) (bool, error) - Checks if a session by key exists
  • Set(sessionKey string, value string, seconds int64, options SessionOptions) error - Set sets a key in store
  • SetAny(key string, value any, seconds int64, options SessionOptions) error - convenience method which saves the supplied interface value, use GetAny to extract
  • MergeMap(key string, mergeMap map[string]any, seconds int64, options SessionOptions) error - updates an existing map
  • SetMap(key string, value map[string]any, seconds int64, options SessionOptions) error - convenience method which saves the supplied map, use GetMap to extract

Usage

sessionKey  := "ABCDEFG"
sessionExpireSeconds = 2*60*60

// Create new / update existing session
sessionStore.Set(sessionKey, sessionValue, sessionExpireSeconds, SessionOptions{})

// Get session value, or default if not found
value := sessionStore.Get(sessionKey, defaultValue, SessionOptions{})

// Delete session
isDeleted, err := sessionStore.Delete(sessionKey, SessionOptions{})
// Store interface value
sessionStore.SetAny(sessionKey, sessionValue, sessionExpireSeconds, SessionOptions{})

// Get interface value
value := sessionStore.GetAny(sessionKey, defaultValue, SessionOptions{})



// Example
value := map[string]string{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
}
isSaved, err := store.SetJSON("mykey", value, 5*60, SessionOptions{})

if !isSaved {
  log.Fatal("Set failed: " + err.Error())
}

result, err := store.GetJSON("mykey", "{}", SessionOptions{})

if err != nil {
  log.Fatal("Get failed: " + err.Error())
}

var res = map[string]string{}
for k, v := range result.(map[string]interface{}) {
  res[k] = v.(string)
}

log.Println(res["key1"])

Changelog

2024.01.03 - Added "Extend" method

2023.08.03 - Renamed "SetJSON", "GetJSON" methods to "SetAny", "GetAny"

2023.08.03 - Added "SetMap", "GetMap", "MergeMap" methods

2022.12.06 - Changed store setup to use struct

2022.01.01 - Added "Has" method

2021.12.15 - Added LICENSE

2021.12.15 - Added test badge

2021.12.15 - Added SetJSON GetJSON

2021.12.14 - Added support for DB dialects

2021.12.14 - Removed GORM dependency and moved to the standard library

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type NewStoreOptions added in v0.15.0

type NewStoreOptions struct {
	SessionTableName   string
	DB                 *sql.DB
	DbDriverName       string
	TimeoutSeconds     int64
	AutomigrateEnabled bool
	DebugEnabled       bool
}

NewStoreOptions define the options for creating a new session store

type Session

type Session struct {
	ID        string     `db:"id"`            // varchar(40), primary key
	Key       string     `db:"session_key"`   // varchar(40)
	UserID    string     `db:"user_id"`       // varchar(40)
	IPAddress string     `db:"ip_address"`    // varchar(50)
	UserAgent string     `db:"user_agent"`    // varchar(1024)
	Value     string     `db:"session_value"` // long text
	ExpiresAt *time.Time `db:"expires_at"`    // datetime NOT NULL
	CreatedAt time.Time  `db:"created_at"`    // datetime NOT NULL
	UpdatedAt time.Time  `db:"updated_at"`    // datetime NOT NULL
	DeletedAt *time.Time `db:"deleted_at"`    // datetime DEFAULT NULL
}

Session type

type SessionOptions added in v0.20.0

type SessionOptions struct {
	UserID    string
	IPAddress string
	UserAgent string
}

type Store

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

Store defines a session store

func NewStore

func NewStore(opts NewStoreOptions) (*Store, error)

NewStore creates a new session store

func (*Store) AutoMigrate

func (st *Store) AutoMigrate() error

AutoMigrate auto migrate

func (*Store) Delete

func (st *Store) Delete(sessionKey string, options SessionOptions) (bool, error)

Delete deletes a session

func (*Store) DriverName

func (st *Store) DriverName(db *sql.DB) string

DriverName finds the driver name from database

func (*Store) EnableDebug

func (st *Store) EnableDebug(debug bool)

EnableDebug - enables the debug option

func (*Store) ExpireSessionGoroutine

func (st *Store) ExpireSessionGoroutine() error

ExpireSessionGoroutine - soft deletes expired cache

func (*Store) Extend added in v0.22.0

func (st *Store) Extend(sessionKey string, seconds int64, options SessionOptions) error

func (*Store) FindByKey

func (st *Store) FindByKey(sessionKey string, options SessionOptions) (*Session, error)

FindByKey finds a session by key

func (*Store) Get

func (st *Store) Get(sessionKey string, valueDefault string, options SessionOptions) (string, error)

Gets the session value as a string

func (*Store) GetAny added in v0.19.0

func (st *Store) GetAny(key string, valueDefault interface{}, options SessionOptions) (interface{}, error)

GetAny attempts to parse the value as interface, use with SetAny

func (*Store) GetMap added in v0.19.0

func (st *Store) GetMap(key string, valueDefault map[string]any, options SessionOptions) (map[string]any, error)

GetMap attempts to parse the value as map[string]any, use with SetMap

func (*Store) Has added in v0.9.0

func (st *Store) Has(sessionKey string, options SessionOptions) (bool, error)

Has finds if a session by key exists

func (*Store) MergeMap added in v0.19.0

func (st *Store) MergeMap(key string, mergeMap map[string]any, seconds int64, options SessionOptions) error

func (*Store) SQLCreateTable

func (st *Store) SQLCreateTable() string

SQLCreateTable returns a SQL string for creating the cache table

func (*Store) Set

func (st *Store) Set(sessionKey string, value string, seconds int64, options SessionOptions) error

Set sets a key in store

func (*Store) SetAny added in v0.19.0

func (st *Store) SetAny(key string, value interface{}, seconds int64, options SessionOptions) error

SetAny convenience method which saves the supplied interface value, use GetAny to extract Internally it serializes the data to JSON

func (*Store) SetMap added in v0.19.0

func (st *Store) SetMap(key string, value map[string]any, seconds int64, options SessionOptions) error

SetMap convenience method which saves the supplied map, use GetMap to extract

type StoreInterface added in v0.20.0

type StoreInterface interface {
	EnableDebug(debug bool)
	AutoMigrate() error
	Extend(sessionKey string, seconds int64, options SessionOptions) error
	Get(key string, valueDefault string, options SessionOptions) (string, error)
	GetAny(key string, valueDefault interface{}, options SessionOptions) (interface{}, error)
	GetMap(key string, valueDefault map[string]any, options SessionOptions) (map[string]any, error)
	MergeMap(key string, mergeMap map[string]any, seconds int64, options SessionOptions) error
	Set(key string, value string, seconds int64, options SessionOptions) error
	SetAny(key string, value interface{}, seconds int64, options SessionOptions) error
	SetMap(key string, value map[string]any, seconds int64, options SessionOptions) error
	Delete(sessionKey string, options SessionOptions) (bool, error)
	DriverName(db *sql.DB) string
}

Jump to

Keyboard shortcuts

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