session

package
v0.1.36 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

session/memory.go

session/middleware.go

session/redis.go

session/session.go

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound       = errors.New("session: not found")
	ErrExpired        = errors.New("session: expired")
	ErrInvalidSession = errors.New("session: invalid session")
)

Common errors

Functions

func Flash

func Flash(session *Session, key string, value any)

Flash stores a message that will be deleted after being read. Useful for one-time messages like "Login successful".

func GetFlash

func GetFlash(session *Session, key string) (any, bool)

GetFlash retrieves and removes a flash message.

func GetFlashString

func GetFlashString(session *Session, key string) string

GetFlashString retrieves and removes a flash message as a string.

func Middleware

func Middleware(m *Manager) func(http.Handler) http.Handler

Middleware returns HTTP middleware that loads sessions automatically. The session is available via FromContext(r.Context()).

func RequireKey

func RequireKey(key string) func(http.Handler) http.Handler

RequireKey middleware returns 401 if the session doesn't have a specific key.

func RequireSession

func RequireSession(m *Manager) func(http.Handler) http.Handler

RequireSession middleware returns 401 if no valid session exists.

Types

type Config

type Config struct {
	// CookieName is the name of the session cookie.
	// Default: "session_id".
	CookieName string

	// MaxAge is the session lifetime.
	// Default: 24 hours.
	MaxAge time.Duration

	// Path is the cookie path.
	// Default: "/".
	Path string

	// Domain is the cookie domain.
	// Default: "" (current domain).
	Domain string

	// Secure sets the Secure flag on the cookie.
	// Default: true.
	Secure bool

	// HttpOnly sets the HttpOnly flag on the cookie.
	// Default: true.
	HttpOnly bool

	// SameSite sets the SameSite attribute.
	// Default: http.SameSiteLaxMode.
	SameSite http.SameSite

	// IDGenerator generates session IDs.
	// Default: cryptographically secure random ID.
	IDGenerator func() (string, error)
}

Config configures the session manager.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults.

type Manager

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

Manager handles session creation, retrieval, and persistence.

func NewManager

func NewManager(store Store, cfg Config) *Manager

NewManager creates a session manager with the given store and config.

func (*Manager) Close

func (m *Manager) Close() error

Close closes the session manager and underlying store.

func (*Manager) Destroy

func (m *Manager) Destroy(w http.ResponseWriter, r *http.Request, session *Session) error

Destroy deletes the session and clears the cookie.

func (*Manager) Get

func (m *Manager) Get(r *http.Request) (*Session, error)

Get retrieves the session from the request, creating a new one if needed.

func (*Manager) New

func (m *Manager) New() (*Session, error)

New creates a new session.

func (*Manager) Refresh

func (m *Manager) Refresh(w http.ResponseWriter, r *http.Request, session *Session) error

Refresh extends the session expiration.

func (*Manager) Regenerate

func (m *Manager) Regenerate(w http.ResponseWriter, r *http.Request, session *Session) error

Regenerate creates a new session ID while preserving data. Use this after authentication to prevent session fixation attacks.

func (*Manager) Save

func (m *Manager) Save(w http.ResponseWriter, r *http.Request, session *Session) error

Save persists the session and sets the cookie.

func (*Manager) Store

func (m *Manager) Store() Store

Store returns the underlying session store.

type MemoryStore

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

MemoryStore implements in-memory session storage.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory session store.

func NewMemoryStoreWithConfig

func NewMemoryStoreWithConfig(cfg MemoryStoreConfig) *MemoryStore

NewMemoryStoreWithConfig creates a memory store with custom configuration.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

Close stops the cleanup goroutine.

func (*MemoryStore) Delete

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

Delete removes a session by ID.

func (*MemoryStore) Load

func (s *MemoryStore) Load(ctx context.Context, id string) (*SessionData, error)

Load retrieves session data by ID.

func (*MemoryStore) Save

func (s *MemoryStore) Save(ctx context.Context, data *SessionData) error

Save stores session data.

func (*MemoryStore) Size

func (s *MemoryStore) Size() int

Size returns the number of sessions.

type MemoryStoreConfig

type MemoryStoreConfig struct {
	// CleanupInterval is how often to remove expired sessions.
	// Default: 10 minutes.
	CleanupInterval time.Duration
}

MemoryStoreConfig configures the memory store.

type RedisStore

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

RedisStore implements Redis-backed session storage.

func ConnectRedis

func ConnectRedis(addr, password string, db int) (*RedisStore, error)

ConnectRedis creates a Redis store with simple connection parameters.

func NewRedisStore

func NewRedisStore(client redis.UniversalClient) *RedisStore

NewRedisStore creates a Redis store with an existing client.

func NewRedisStoreWithConfig

func NewRedisStoreWithConfig(cfg RedisStoreConfig) (*RedisStore, error)

NewRedisStoreWithConfig creates a Redis store with custom configuration.

func (*RedisStore) Client

func (s *RedisStore) Client() redis.UniversalClient

Client returns the underlying Redis client.

func (*RedisStore) Close

func (s *RedisStore) Close() error

Close closes the Redis connection.

func (*RedisStore) Delete

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

Delete removes a session by ID.

func (*RedisStore) Load

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

Load retrieves session data by ID.

func (*RedisStore) Save

func (s *RedisStore) Save(ctx context.Context, data *SessionData) error

Save stores session data.

type RedisStoreConfig

type RedisStoreConfig struct {
	// Client is an existing Redis client.
	// If provided, other connection options are ignored.
	Client redis.UniversalClient

	// Address is the Redis server address.
	Address string

	// Password for Redis authentication.
	Password string

	// DB is the database number.
	DB int

	// KeyPrefix is prepended to session keys.
	// Default: "session:".
	KeyPrefix string

	// PoolSize is the connection pool size.
	// Default: 10.
	PoolSize int
}

RedisStoreConfig configures the Redis store.

type Session

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

Session represents a user session with key-value data.

func FromContext

func FromContext(ctx context.Context) *Session

FromContext retrieves the session from the request context. Returns nil if no session is in context (middleware not used).

func MustFromContext

func MustFromContext(ctx context.Context) *Session

MustFromContext retrieves the session from context, panicking if not found.

func (*Session) Clear

func (s *Session) Clear()

Clear removes all values from the session.

func (*Session) Delete

func (s *Session) Delete(key string)

Delete removes a value from the session.

func (*Session) ExpiresAt

func (s *Session) ExpiresAt() time.Time

ExpiresAt returns when the session expires.

func (*Session) Get

func (s *Session) Get(key string) (any, bool)

Get retrieves a value from the session.

func (*Session) GetBool

func (s *Session) GetBool(key string) bool

GetBool retrieves a bool value.

func (*Session) GetInt

func (s *Session) GetInt(key string) int

GetInt retrieves an int value.

func (*Session) GetString

func (s *Session) GetString(key string) string

GetString retrieves a string value.

func (*Session) GetTime

func (s *Session) GetTime(key string) time.Time

GetTime retrieves a time value.

func (*Session) ID

func (s *Session) ID() string

ID returns the session ID.

func (*Session) IsNew

func (s *Session) IsNew() bool

IsNew returns true if the session was just created.

func (*Session) Keys

func (s *Session) Keys() []string

Keys returns all keys in the session.

func (*Session) Modified

func (s *Session) Modified() bool

Modified returns true if the session data has been changed.

func (*Session) Set

func (s *Session) Set(key string, value any)

Set stores a value in the session.

func (*Session) Values

func (s *Session) Values() map[string]any

Values returns a copy of all session data.

type SessionData

type SessionData struct {
	ID        string         `json:"id"`
	Data      map[string]any `json:"data"`
	ExpiresAt time.Time      `json:"expires_at"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
}

SessionData is the serializable session data stored in backends.

func (*SessionData) MarshalBinary

func (s *SessionData) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler.

func (*SessionData) UnmarshalBinary

func (s *SessionData) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler.

type Store

type Store interface {
	// Load retrieves session data by ID.
	// Returns ErrNotFound if the session doesn't exist.
	Load(ctx context.Context, id string) (*SessionData, error)

	// Save stores session data.
	Save(ctx context.Context, data *SessionData) error

	// Delete removes a session by ID.
	Delete(ctx context.Context, id string) error

	// Close releases any resources.
	Close() error
}

Store defines the interface for session storage backends.

Jump to

Keyboard shortcuts

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