session

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 11 Imported by: 1

README

session-kit

A Go library for session management with support for memory and Redis storage backends. Compatible with Fiber v2's session middleware.

Features

  • Multiple Storage Backends: Memory (for development) and Redis (for production)
  • Fiber v2 Compatible: Implements fiber.Storage interface
  • Factory Pattern: Easy storage creation with configuration
  • Session Management: High-level session operations with SessionData struct
  • Fluent Configuration: Builder pattern for easy configuration
  • Automatic Expiration: TTL-based session expiration
  • Thread-Safe: Safe for concurrent access

Installation

go get github.com/soulteary/session-kit

Quick Start

Memory Storage (Development)
package main

import (
    "time"
    session "github.com/soulteary/session-kit"
)

func main() {
    // Create memory storage
    storage := session.NewMemoryStorage("session:", 10*time.Minute)
    defer storage.Close()

    // Use storage
    storage.Set("session-123", []byte("data"), time.Hour)
    data, _ := storage.Get("session-123")
}
Redis Storage (Production)
package main

import (
    session "github.com/soulteary/session-kit"
)

func main() {
    // Create Redis storage
    storage, err := session.NewRedisStorageFromConfig(
        "localhost:6379",  // addr
        "",                // password
        0,                 // db
        "myapp:session:",  // key prefix
    )
    if err != nil {
        panic(err)
    }
    defer storage.Close()
}
Using Factory Pattern
package main

import (
    session "github.com/soulteary/session-kit"
)

func main() {
    // Create storage from configuration
    cfg := session.DefaultStorageConfig().
        WithType(session.StorageTypeRedis).
        WithRedisAddr("localhost:6379").
        WithKeyPrefix("myapp:session:")

    storage, err := session.NewStorage(cfg)
    if err != nil {
        panic(err)
    }
    defer storage.Close()
}
Using with Fiber
package main

import (
    "github.com/gofiber/fiber/v2"
    fibersession "github.com/gofiber/fiber/v2/middleware/session"
    session "github.com/soulteary/session-kit"
)

func main() {
    app := fiber.New()

    // Create session manager
    storage := session.NewMemoryStorage("session:", 0)
    config := session.DefaultConfig().
        WithCookieName("my_session").
        WithExpiration(24 * time.Hour)

    manager := session.NewManager(storage, config)

    // Create Fiber session store
    store := fibersession.New(manager.FiberSessionConfig())

    app.Get("/", func(c *fiber.Ctx) error {
        sess, _ := store.Get(c)

        if session.IsAuthenticated(sess) {
            return c.SendString("Hello, " + session.GetUserID(sess))
        }

        return c.SendString("Please login")
    })

    app.Post("/login", func(c *fiber.Ctx) error {
        sess, _ := store.Get(c)

        session.SetUserID(sess, "user-123")
        session.SetEmail(sess, "user@example.com")
        session.AddAMR(sess, "pwd")
        session.Authenticate(sess)

        return c.SendString("Logged in")
    })

    app.Listen(":3000")
}

Configuration

Session Config
cfg := session.DefaultConfig().
    WithExpiration(24 * time.Hour).   // Session duration
    WithCookieName("my_session").     // Cookie name
    WithCookieDomain(".example.com"). // Cookie domain
    WithCookiePath("/").              // Cookie path
    WithSecure(true).                 // HTTPS only
    WithHTTPOnly(true).               // No JS access
    WithSameSite("Lax").              // SameSite policy
    WithKeyPrefix("myapp:session:")   // Storage key prefix
Storage Config
cfg := session.DefaultStorageConfig().
    WithType(session.StorageTypeRedis).      // memory or redis
    WithKeyPrefix("session:").               // Key prefix
    WithRedisAddr("localhost:6379").         // Redis address
    WithRedisPassword("secret").             // Redis password
    WithRedisDB(0).                          // Redis database
    WithMemoryGCInterval(10 * time.Minute)   // Memory GC interval

Session Data

The SessionData struct provides a rich model for session data:

session := session.NewSessionData("session-123", time.Hour)

// User info
session.UserID = "user-456"
session.Email = "user@example.com"
session.Phone = "+1234567890"
session.Authenticated = true

// Authentication methods (AMR)
session.AddAMR("pwd")     // Password
session.AddAMR("otp")     // OTP
session.HasAMR("pwd")     // Check if has method

// Authorization scopes
session.AddScope("read")
session.AddScope("write")
session.HasScope("read")  // Check if has scope

// Custom data
session.SetValue("custom", "value")
val, ok := session.GetValue("custom")

// State checks
session.IsExpired()
session.IsAuthenticated()
session.Touch()  // Update last access time

Fiber Session Helpers

Helper functions for working with Fiber sessions:

// Authentication
session.Authenticate(sess)      // Mark as authenticated
session.Unauthenticate(sess)    // Destroy session
session.IsAuthenticated(sess)   // Check if authenticated

// User info
session.SetUserID(sess, "user-123")
session.GetUserID(sess)

session.SetEmail(sess, "user@example.com")
session.GetEmail(sess)

session.SetPhone(sess, "+1234567890")
session.GetPhone(sess)

// AMR (Authentication Methods References)
session.SetAMR(sess, []string{"pwd", "otp"})
session.GetAMR(sess)
session.AddAMR(sess, "pwd")
session.HasAMR(sess, "pwd")

// Scopes
session.SetScopes(sess, []string{"read", "write"})
session.GetScopes(sess)
session.HasScope(sess, "read")

// Timestamps
session.UpdateLastAccess(sess)
session.GetLastAccess(sess)
session.GetCreatedAt(sess)

License

Apache License 2.0

Documentation

Overview

Package session provides session storage and management functionality.

Index

Constants

View Source
const (
	KeyAuthenticated = "authenticated"
	KeyUserID        = "user_id"
	KeyEmail         = "email"
	KeyPhone         = "phone"
	KeyAMR           = "amr"
	KeyScopes        = "scopes"
	KeyCreatedAt     = "created_at"
	KeyLastAccess    = "last_access"
)

SessionKeys defines common session key names.

Variables

This section is empty.

Functions

func AddAMR

func AddAMR(session *fibersession.Session, method string)

AddAMR adds an authentication method reference to a fiber session.

func Authenticate

func Authenticate(session *fibersession.Session) error

Authenticate marks a fiber session as authenticated.

func CreateCookie

func CreateCookie(config Config, sessionID string) *fiber.Cookie

CreateCookie creates a fiber.Cookie for session sharing across domains.

func GetAMR

func GetAMR(session *fibersession.Session) []string

GetAMR gets the authentication methods references from a fiber session.

func GetCreatedAt

func GetCreatedAt(session *fibersession.Session) time.Time

GetCreatedAt gets the session creation timestamp from a fiber session.

func GetEmail

func GetEmail(session *fibersession.Session) string

GetEmail gets the email from a fiber session.

func GetLastAccess

func GetLastAccess(session *fibersession.Session) time.Time

GetLastAccess gets the last access timestamp from a fiber session.

func GetPhone

func GetPhone(session *fibersession.Session) string

GetPhone gets the phone from a fiber session.

func GetScopes

func GetScopes(session *fibersession.Session) []string

GetScopes gets the authorization scopes from a fiber session.

func GetUserID

func GetUserID(session *fibersession.Session) string

GetUserID gets the user ID from a fiber session.

func HasAMR

func HasAMR(session *fibersession.Session, method string) bool

HasAMR checks if a fiber session has a specific authentication method.

func HasScope

func HasScope(session *fibersession.Session, scope string) bool

HasScope checks if a fiber session has a specific scope.

func IsAuthenticated

func IsAuthenticated(session *fibersession.Session) bool

IsAuthenticated checks if a fiber session is authenticated.

func SetAMR

func SetAMR(session *fibersession.Session, amr []string)

SetAMR sets the authentication methods references in a fiber session.

func SetEmail

func SetEmail(session *fibersession.Session, email string)

SetEmail sets the email in a fiber session.

func SetPhone

func SetPhone(session *fibersession.Session, phone string)

SetPhone sets the phone in a fiber session.

func SetScopes

func SetScopes(session *fibersession.Session, scopes []string)

SetScopes sets the authorization scopes in a fiber session.

func SetUserID

func SetUserID(session *fibersession.Session, userID string)

SetUserID sets the user ID in a fiber session.

func Unauthenticate

func Unauthenticate(session *fibersession.Session) error

Unauthenticate destroys a fiber session. Note: session.Destroy() requires a valid context (ctx). If session has been previously saved, the context may be released. This function handles nil session gracefully.

func UpdateLastAccess

func UpdateLastAccess(session *fibersession.Session)

UpdateLastAccess updates the last access timestamp in a fiber session.

Types

type Config

type Config struct {
	// Expiration is the session expiration duration.
	// Default: 24 hours
	Expiration time.Duration

	// CookieName is the name of the session cookie.
	// Default: "session_id"
	CookieName string

	// CookieDomain is the domain for the session cookie.
	// If empty, the cookie will be set for the current domain only.
	// Default: "" (empty)
	CookieDomain string

	// CookiePath is the path for the session cookie.
	// Default: "/"
	CookiePath string

	// Secure indicates if the cookie should only be sent over HTTPS.
	// Default: true
	Secure bool

	// HTTPOnly indicates if the cookie should be inaccessible to JavaScript.
	// Default: true
	HTTPOnly bool

	// SameSite controls the SameSite attribute of the cookie.
	// Allowed values: "Strict", "Lax", "None"
	// Default: "Lax"
	SameSite string

	// KeyPrefix is the prefix for session keys in storage.
	// Default: "session:"
	KeyPrefix string
}

Config represents session configuration options.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible default values.

func (Config) Validate

func (c Config) Validate() error

Validate validates the configuration and returns an error if invalid. Note: This method uses a value receiver, so it cannot modify the config. Use DefaultConfig() with builder methods to ensure valid configuration.

func (Config) WithCookieDomain

func (c Config) WithCookieDomain(domain string) Config

WithCookieDomain sets the session cookie domain.

func (Config) WithCookieName

func (c Config) WithCookieName(name string) Config

WithCookieName sets the session cookie name.

func (Config) WithCookiePath

func (c Config) WithCookiePath(path string) Config

WithCookiePath sets the session cookie path.

func (Config) WithExpiration

func (c Config) WithExpiration(exp time.Duration) Config

WithExpiration sets the session expiration duration.

func (Config) WithHTTPOnly

func (c Config) WithHTTPOnly(httpOnly bool) Config

WithHTTPOnly sets whether the cookie should be inaccessible to JavaScript.

func (Config) WithKeyPrefix

func (c Config) WithKeyPrefix(prefix string) Config

WithKeyPrefix sets the prefix for session keys in storage.

func (Config) WithSameSite

func (c Config) WithSameSite(sameSite string) Config

WithSameSite sets the SameSite attribute of the cookie. Allowed values: "Strict", "Lax", "None"

func (Config) WithSecure

func (c Config) WithSecure(secure bool) Config

WithSecure sets whether the cookie should only be sent over HTTPS.

type KVManager added in v1.1.0

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

KVManager wraps a Store and provides default TTL and a high-level API. Use NewKVManager(store, defaultTTL) then Create/Get/Set/Delete/Exists/Refresh.

func NewKVManager added in v1.1.0

func NewKVManager(store Store, defaultTTL time.Duration) *KVManager

NewKVManager returns a KVManager that uses the given store and default TTL.

func (*KVManager) Create added in v1.1.0

func (m *KVManager) Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (string, error)

Create creates a new session and returns its ID.

func (*KVManager) Delete added in v1.1.0

func (m *KVManager) Delete(ctx context.Context, id string) error

Delete removes the session for the given ID.

func (*KVManager) Exists added in v1.1.0

func (m *KVManager) Exists(ctx context.Context, id string) (bool, error)

Exists reports whether a session exists for the given ID.

func (*KVManager) Get added in v1.1.0

func (m *KVManager) Get(ctx context.Context, id string) (*KVSessionRecord, error)

Get returns the session for the given ID, or an error if not found/expired.

func (*KVManager) Refresh added in v1.1.0

func (m *KVManager) Refresh(ctx context.Context, id string, ttl time.Duration) error

Refresh extends the expiration of the session by setting it again with the given ttl.

func (*KVManager) Set added in v1.1.0

func (m *KVManager) Set(ctx context.Context, id string, data map[string]interface{}, ttl time.Duration) error

Set updates the session for the given ID. If ttl is 0, the implementation may keep existing TTL or use default.

type KVSessionRecord added in v1.1.0

type KVSessionRecord struct {
	ID        string                 `json:"id"`
	Data      map[string]interface{} `json:"data"`
	CreatedAt time.Time              `json:"created_at"`
	ExpiresAt time.Time              `json:"expires_at"`
}

KVSessionRecord is a generic key-value session record for server-side sessions (e.g. Herald). It is not tied to Fiber; use SessionData and Storage for Fiber session backends.

type Manager

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

Manager provides high-level session management operations.

func NewManager

func NewManager(storage Storage, config Config) *Manager

NewManager creates a new session Manager with the given storage and configuration.

func (*Manager) CreateSession

func (m *Manager) CreateSession(id string) *SessionData

CreateSession creates a new session and returns its data.

func (*Manager) DeleteSession

func (m *Manager) DeleteSession(id string) error

DeleteSession removes a session from storage.

func (*Manager) FiberSessionConfig

func (m *Manager) FiberSessionConfig() fibersession.Config

FiberSessionConfig returns a fiber/v2/middleware/session.Config configured to use the Manager's storage.

func (*Manager) GetConfig

func (m *Manager) GetConfig() Config

GetConfig returns the session configuration.

func (*Manager) GetStorage

func (m *Manager) GetStorage() Storage

GetStorage returns the underlying storage.

func (*Manager) LoadSession

func (m *Manager) LoadSession(id string) (*SessionData, error)

LoadSession loads a session from storage.

func (*Manager) SaveSession

func (m *Manager) SaveSession(session *SessionData) error

SaveSession saves a session to storage.

func (*Manager) TouchSession

func (m *Manager) TouchSession(session *SessionData) error

TouchSession updates the last access time and extends expiration.

type MemoryStorage

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

MemoryStorage implements Storage interface using in-memory map. This is useful for development and testing, but not suitable for production with multiple server instances as sessions won't be shared.

func NewMemoryStorage

func NewMemoryStorage(keyPrefix string, gcInterval time.Duration) *MemoryStorage

NewMemoryStorage creates a new in-memory storage. The gcInterval parameter specifies how often to run garbage collection to clean up expired entries. If gcInterval is 0, garbage collection is disabled.

func (*MemoryStorage) Close

func (s *MemoryStorage) Close() error

Close stops the garbage collector and releases resources.

func (*MemoryStorage) Delete

func (s *MemoryStorage) Delete(key string) error

Delete removes the value for the given key. It returns no error if the storage does not contain the key.

func (*MemoryStorage) Get

func (s *MemoryStorage) Get(key string) ([]byte, error)

Get retrieves the value for the given key. Returns nil, nil if the key does not exist or has expired.

func (*MemoryStorage) Len

func (s *MemoryStorage) Len() int

Len returns the number of entries in the storage (including expired ones).

func (*MemoryStorage) Reset

func (s *MemoryStorage) Reset() error

Reset removes all keys with the configured prefix.

func (*MemoryStorage) Set

func (s *MemoryStorage) Set(key string, val []byte, exp time.Duration) error

Set stores the given value for the given key along with an expiration value. If expiration is 0, the value never expires. Empty key or value will be ignored without an error.

type RedisStorage

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

RedisStorage implements Storage interface using Redis. This is suitable for production with multiple server instances as sessions are shared via Redis.

func NewRedisStorage

func NewRedisStorage(client *redis.Client, keyPrefix string) *RedisStorage

NewRedisStorage creates a new Redis storage for sessions. The client parameter should be a valid Redis client. The keyPrefix is prepended to all session keys.

func NewRedisStorageFromConfig

func NewRedisStorageFromConfig(addr, password string, db int, keyPrefix string) (*RedisStorage, error)

NewRedisStorageFromConfig creates a new Redis storage using configuration. This is a convenience function that creates both the Redis client and storage.

func (*RedisStorage) Close

func (s *RedisStorage) Close() error

Close closes the Redis client connection.

func (*RedisStorage) Delete

func (s *RedisStorage) Delete(key string) error

Delete removes the value for the given key. It returns no error if the storage does not contain the key.

func (*RedisStorage) Exists

func (s *RedisStorage) Exists(key string) (bool, error)

Exists checks if a key exists in Redis.

func (*RedisStorage) Expire

func (s *RedisStorage) Expire(key string, exp time.Duration) error

Expire sets a new expiration on a key.

func (*RedisStorage) Get

func (s *RedisStorage) Get(key string) ([]byte, error)

Get retrieves the value for the given key. Returns nil, nil if the key does not exist.

func (*RedisStorage) GetClient

func (s *RedisStorage) GetClient() *redis.Client

GetClient returns the underlying Redis client. This can be useful for advanced operations not covered by the Storage interface.

func (*RedisStorage) GetKeyPrefix

func (s *RedisStorage) GetKeyPrefix() string

GetKeyPrefix returns the key prefix used by this storage.

func (*RedisStorage) GetTTL

func (s *RedisStorage) GetTTL(key string) (time.Duration, error)

GetTTL returns the remaining TTL for a key. Returns -2 if the key does not exist, -1 if the key has no expiration.

func (*RedisStorage) Reset

func (s *RedisStorage) Reset() error

Reset removes all keys with the configured prefix.

func (*RedisStorage) Set

func (s *RedisStorage) Set(key string, val []byte, exp time.Duration) error

Set stores the given value for the given key along with an expiration value. If expiration is 0, the value never expires. Empty key or value will be ignored without an error.

type RedisStore added in v1.1.0

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

RedisStore implements Store using Redis. Keys are prefixed with keyPrefix.

func NewRedisStore added in v1.1.0

func NewRedisStore(client *redis.Client, keyPrefix string) *RedisStore

NewRedisStore creates a Redis-backed Store. keyPrefix is prepended to all keys (e.g. "otp:session:").

func (*RedisStore) Create added in v1.1.0

func (s *RedisStore) Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (string, error)

Create creates a new session and returns its ID.

func (*RedisStore) Delete added in v1.1.0

func (s *RedisStore) Delete(ctx context.Context, id string) error

Delete removes the session for the given ID.

func (*RedisStore) Exists added in v1.1.0

func (s *RedisStore) Exists(ctx context.Context, id string) (bool, error)

Exists reports whether a session exists for the given ID.

func (*RedisStore) Get added in v1.1.0

func (s *RedisStore) Get(ctx context.Context, id string) (*KVSessionRecord, error)

Get returns the session for the given ID, or nil and error if not found/expired.

func (*RedisStore) Set added in v1.1.0

func (s *RedisStore) Set(ctx context.Context, id string, data map[string]interface{}, ttl time.Duration) error

Set stores or updates the session for the given ID with the given ttl. When updating an existing session, CreatedAt is preserved.

type SessionData

type SessionData struct {
	// ID is the unique session identifier.
	ID string `json:"id"`

	// UserID is the authenticated user's ID.
	UserID string `json:"user_id,omitempty"`

	// Email is the authenticated user's email.
	Email string `json:"email,omitempty"`

	// Phone is the authenticated user's phone number.
	Phone string `json:"phone,omitempty"`

	// Authenticated indicates if the session is authenticated.
	Authenticated bool `json:"authenticated"`

	// Data is a map for storing arbitrary session data.
	Data map[string]interface{} `json:"data,omitempty"`

	// CreatedAt is when the session was created.
	CreatedAt time.Time `json:"created_at"`

	// ExpiresAt is when the session expires.
	ExpiresAt time.Time `json:"expires_at"`

	// LastAccessedAt is when the session was last accessed.
	LastAccessedAt time.Time `json:"last_accessed_at"`

	// AMR (Authentication Methods References) records how the user authenticated.
	AMR []string `json:"amr,omitempty"`

	// Scopes are the authorization scopes for this session.
	Scopes []string `json:"scopes,omitempty"`
}

SessionData represents the data stored in a session.

func NewSessionData

func NewSessionData(id string, expiration time.Duration) *SessionData

NewSessionData creates a new SessionData with the given ID and expiration.

func (*SessionData) AddAMR

func (s *SessionData) AddAMR(method string)

AddAMR adds an authentication method reference.

func (*SessionData) AddScope

func (s *SessionData) AddScope(scope string)

AddScope adds an authorization scope.

func (*SessionData) DeleteValue

func (s *SessionData) DeleteValue(key string)

DeleteValue removes a value from the session data map.

func (*SessionData) GetValue

func (s *SessionData) GetValue(key string) (interface{}, bool)

GetValue gets a value from the session data map.

func (*SessionData) HasAMR

func (s *SessionData) HasAMR(method string) bool

HasAMR checks if the session has a specific authentication method.

func (*SessionData) HasScope

func (s *SessionData) HasScope(scope string) bool

HasScope checks if the session has a specific scope.

func (*SessionData) IsAuthenticated

func (s *SessionData) IsAuthenticated() bool

IsAuthenticated returns true if the session is authenticated and not expired.

func (*SessionData) IsExpired

func (s *SessionData) IsExpired() bool

IsExpired checks if the session has expired.

func (*SessionData) SetValue

func (s *SessionData) SetValue(key string, value interface{})

SetValue sets a value in the session data map.

func (*SessionData) Touch

func (s *SessionData) Touch()

Touch updates the last accessed time to now.

type Storage

type Storage interface {
	// Get retrieves the value for the given key.
	// Returns nil, nil if the key does not exist.
	Get(key string) ([]byte, error)

	// Set stores the given value for the given key along with an expiration value.
	// If expiration is 0, the value never expires.
	// Empty key or value will be ignored without an error.
	Set(key string, val []byte, exp time.Duration) error

	// Delete removes the value for the given key.
	// It returns no error if the storage does not contain the key.
	Delete(key string) error

	// Reset removes all keys with the configured prefix.
	Reset() error

	// Close closes the storage connection.
	Close() error
}

Storage is the interface for session storage backends. This interface is compatible with fiber.Storage interface.

func MustNewStorage

func MustNewStorage(cfg StorageConfig) Storage

MustNewStorage creates a new Storage instance or panics if an error occurs. This is useful for initialization in main() where errors should be fatal.

func NewStorage

func NewStorage(cfg StorageConfig) (Storage, error)

NewStorage creates a new Storage instance based on the configuration. It automatically selects the appropriate storage backend based on the Type field.

func NewStorageFromEnv

func NewStorageFromEnv(redisEnabled bool, redisAddr, redisPassword string, redisDB int, keyPrefix string) (Storage, error)

NewStorageFromEnv creates a Storage based on environment-like configuration. If redisEnabled is true, it creates a Redis storage; otherwise, it creates a memory storage. This is a convenience function for common use cases.

type StorageConfig

type StorageConfig struct {
	// Type is the storage backend type.
	Type StorageType

	// KeyPrefix is the prefix for session keys.
	KeyPrefix string

	// RedisAddr is the Redis server address (for Redis storage).
	RedisAddr string

	// RedisPassword is the Redis password (for Redis storage).
	RedisPassword string

	// RedisDB is the Redis database number (for Redis storage).
	RedisDB int

	// RedisClient is an existing Redis client (for Redis storage).
	// If provided, RedisAddr, RedisPassword, and RedisDB are ignored.
	RedisClient *redis.Client

	// MemoryGCInterval is the garbage collection interval for memory storage.
	// Default: 10 minutes. Set to 0 to disable GC.
	MemoryGCInterval time.Duration
}

StorageConfig represents configuration for creating a storage backend.

func DefaultStorageConfig

func DefaultStorageConfig() StorageConfig

DefaultStorageConfig returns a StorageConfig with default values.

func (StorageConfig) WithKeyPrefix

func (c StorageConfig) WithKeyPrefix(prefix string) StorageConfig

WithKeyPrefix sets the key prefix.

func (StorageConfig) WithMemoryGCInterval

func (c StorageConfig) WithMemoryGCInterval(interval time.Duration) StorageConfig

WithMemoryGCInterval sets the memory storage garbage collection interval.

func (StorageConfig) WithRedisAddr

func (c StorageConfig) WithRedisAddr(addr string) StorageConfig

WithRedisAddr sets the Redis address.

func (StorageConfig) WithRedisClient

func (c StorageConfig) WithRedisClient(client *redis.Client) StorageConfig

WithRedisClient sets an existing Redis client.

func (StorageConfig) WithRedisDB

func (c StorageConfig) WithRedisDB(db int) StorageConfig

WithRedisDB sets the Redis database number.

func (StorageConfig) WithRedisPassword

func (c StorageConfig) WithRedisPassword(password string) StorageConfig

WithRedisPassword sets the Redis password.

func (StorageConfig) WithType

func (c StorageConfig) WithType(t StorageType) StorageConfig

WithType sets the storage type.

type StorageType

type StorageType string

StorageType represents the type of storage backend.

const (
	// StorageTypeMemory uses in-memory storage.
	StorageTypeMemory StorageType = "memory"
	// StorageTypeRedis uses Redis storage.
	StorageTypeRedis StorageType = "redis"
)

type Store added in v1.1.0

type Store interface {
	Create(ctx context.Context, data map[string]interface{}, ttl time.Duration) (id string, err error)
	Get(ctx context.Context, id string) (*KVSessionRecord, error)
	Set(ctx context.Context, id string, data map[string]interface{}, ttl time.Duration) error
	Delete(ctx context.Context, id string) error
	Exists(ctx context.Context, id string) (bool, error)
}

Store is a generic KV session store for server-side sessions. Used by services like Herald that need Create/Get/Set/Delete/Exists with TTL.

Jump to

Keyboard shortcuts

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