session

package
v2.0.0-...-51e8ac7 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package session provides pluggable session and flash management for v2.

The Store interface abstracts session persistence. The default CookieStore stores signed session data in an HTTP cookie. Alternative implementations (Redis, database) can use the opaque token as a session ID.

Flash provides one-shot messages that survive a single redirect.

Index

Constants

View Source
const FlashKey = "_v2_flash"

FlashKey is the local storage key for the *Flash on the request parser.

View Source
const SessionKey = "_v2_session"

SessionKey is the local storage key for the *Session on the request parser.

Variables

This section is empty.

Functions

func GetTyped

func GetTyped[T any](s *Session, key string) (T, error)

GetTyped retrieves a value and type-asserts it to T. Returns an error if the key does not exist or the value is not of type T. This eliminates the need for runtime type assertions in handlers.

func Middleware

func Middleware(manager *Manager, cookieName string) func(next func(*v2wf.RequestContext) error) func(*v2wf.RequestContext) error

Middleware returns a v2 middleware that loads the session from the request cookie and registers a before-commit hook to persist any dirty session state back to the response cookie.

The middleware stores the *Session and *Flash on the request parser's locals (SessionKey and FlashKey) so handlers can access them via FromContext.

Session save failures are handled in strict mode (default): the error is logged via webFramework.AddLog and propagated to the caller so the response is not committed as a success. Use MiddlewareWithConfig to select best-effort mode if needed.

func MiddlewareWithConfig

func MiddlewareWithConfig(cfg MiddlewareConfig) func(next func(*v2wf.RequestContext) error) func(*v2wf.RequestContext) error

MiddlewareWithConfig returns a v2 middleware configured by the given MiddlewareConfig. See Middleware for behavior details.

func SaveFlashToSession

func SaveFlashToSession(s *Session, f *Flash)

SaveFlashToSession stores active (unconsumed) flash entries into a session.

func SetTyped

func SetTyped[T any](s *Session, key string, value T)

SetTyped stores a value of type T. This is a convenience wrapper around Set that preserves compile-time type information at the call site.

Types

type CookieStore

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

CookieStore implements Store using HMAC-signed cookies.

func NewCookieStore

func NewCookieStore(config CookieStoreConfig) (*CookieStore, error)

NewCookieStore creates a CookieStore with the given configuration. Returns an error if SecretKey is shorter than 32 bytes.

func (*CookieStore) Config

func (s *CookieStore) Config() CookieStoreConfig

Config returns the store configuration.

func (*CookieStore) Delete

func (s *CookieStore) Delete(_ context.Context, _ string) error

Delete is a no-op for CookieStore; the caller should expire the cookie.

func (*CookieStore) Load

func (s *CookieStore) Load(_ context.Context, token string) (*Session, error)

Load decodes and verifies a signed cookie token into a Session.

func (*CookieStore) Save

func (s *CookieStore) Save(_ context.Context, sess *Session) (string, error)

Save encodes and signs a Session into an opaque cookie token.

type CookieStoreConfig

type CookieStoreConfig struct {
	// SecretKey is the HMAC signing key. Must be at least 32 bytes.
	SecretKey []byte

	// VerificationKeys are additional keys for key rotation.
	// The store verifies against SecretKey first, then each verification key.
	VerificationKeys [][]byte

	// EncryptionKey, when set (must be 32 bytes), enables AES-GCM encryption.
	// When nil, the payload is signed but readable by the client.
	EncryptionKey []byte

	// CookieName is the HTTP cookie name. Default: "requestcore_session".
	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.
	Domain string

	// Secure sets the cookie Secure flag. Default: false (set true in production).
	Secure bool

	// HttpOnly sets the cookie HttpOnly flag. Default: true.
	// Use a pointer to distinguish "not set" (nil → defaults to true)
	// from "explicitly set to false" (allows disabling HttpOnly for
	// cross-site JavaScript access when needed).
	HttpOnly *bool

	// SameSite sets the cookie SameSite attribute.
	// Values: "lax", "strict", "none". Default: "lax".
	SameSite string

	// MaxPayloadSize is the maximum encoded cookie payload size in bytes.
	// Default: 3800 (safe for most browsers).
	MaxPayloadSize int
}

CookieStoreConfig configures a CookieStore.

type Flash

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

Flash provides one-shot messages that survive a single redirect. Reading a flash value consumes it for the next save cycle.

func FlashFromContext

func FlashFromContext(ctx *v2wf.RequestContext) *Flash

FlashFromContext retrieves the *Flash from the request context's parser locals. Returns nil if no session middleware was applied.

func LoadFlashFromSession

func LoadFlashFromSession(s *Session) *Flash

LoadFlashFromSession creates a Flash populated from session data. It handles both map[string]string (direct) and map[string]any (after JSON round-trip through CookieStore) flash data.

func NewFlash

func NewFlash() *Flash

NewFlash creates a new empty Flash.

func (*Flash) ActiveEntries

func (f *Flash) ActiveEntries() map[string]string

ActiveEntries returns the flash entries that have not been consumed.

func (*Flash) Add

func (f *Flash) Add(key, value string)

Add stores a flash message by key.

func (*Flash) Clear

func (f *Flash) Clear()

Clear marks all flash entries as consumed.

func (*Flash) ConsumedEntries

func (f *Flash) ConsumedEntries() []string

ConsumedEntries returns the keys that have been read and should be removed on the next save cycle.

func (*Flash) Get

func (f *Flash) Get(key string) string

Get retrieves a flash message by key and marks it as read (consumed). Returns "" if the key does not exist or has already been consumed.

func (*Flash) GetAll

func (f *Flash) GetAll() map[string]string

GetAll returns all unconsumed flash entries and marks them as read (consumed).

func (*Flash) Has

func (f *Flash) Has(key string) bool

Has reports whether a flash key exists and has not been consumed.

func (*Flash) Peek

func (f *Flash) Peek(key string) string

Peek retrieves a flash message by key without marking it as read. Returns "" if the key does not exist or has already been consumed.

type Manager

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

Manager coordinates session and flash lifecycle across HTTP requests. It is initialized with a Store and provides methods for loading sessions from request cookies and saving them to response cookies.

func NewManager

func NewManager(store Store) *Manager

NewManager creates a session Manager backed by the given Store.

func (*Manager) ExpireCookie

func (m *Manager) ExpireCookie(cookieName string) *http.Cookie

ExpireCookie returns a cookie that immediately expires the session cookie.

func (*Manager) LoadFromCookie

func (m *Manager) LoadFromCookie(ctx context.Context, cookieName, cookieValue string) (*Session, *Flash, error)

LoadFromCookie extracts the session token from the named cookie and loads the session from the store. If the cookie is absent, a new empty session is returned.

func (*Manager) SaveToCookie

func (m *Manager) SaveToCookie(ctx context.Context, sess *Session, flash *Flash, cookieName string) (*http.Cookie, error)

SaveToCookie persists the session and returns an http.Cookie to set on the response. If the session is not dirty, the cookie is not modified (returns nil).

func (*Manager) Store

func (m *Manager) Store() Store

Store returns the underlying session store.

type MiddlewareConfig

type MiddlewareConfig struct {
	// Manager is the session manager used to load and save sessions.
	Manager *Manager

	// CookieName is the name of the session cookie.
	CookieName string

	// SaveFailureMode controls how session save failures are handled.
	// Default: SaveStrict.
	SaveFailureMode SaveFailureMode
}

MiddlewareConfig configures the session middleware.

type NoOpStore

type NoOpStore struct{}

NoOpStore is a Store implementation that does nothing. It is useful for testing and for applications that do not need sessions.

func (NoOpStore) Delete

func (NoOpStore) Delete(_ context.Context, _ string) error

Delete is a no-op.

func (NoOpStore) Load

func (NoOpStore) Load(_ context.Context, _ string) (*Session, error)

Load always returns a new empty session.

func (NoOpStore) Save

func (NoOpStore) Save(_ context.Context, s *Session) (string, error)

Save returns the session ID unchanged.

type SaveFailureMode

type SaveFailureMode int

SaveFailureMode controls how the session middleware handles session save failures in the before-commit hook.

const (
	// SaveStrict (default) propagates save failures to the caller so
	// the response is not committed as a success. The failure is also
	// logged via webFramework.AddLog with the "session-save-failed" key.
	SaveStrict SaveFailureMode = iota
	// SaveBestEffort logs save failures via webFramework.AddLog but
	// does not propagate the error, allowing the response to commit
	// successfully even if the session was not persisted.
	SaveBestEffort
)

type Session

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

Session represents a user session with key-value storage.

func FromContext

func FromContext(ctx *v2wf.RequestContext) *Session

FromContext retrieves the *Session from the request context's parser locals. Returns nil if no session middleware was applied.

func NewSession

func NewSession(store Store) *Session

NewSession creates a new empty session backed by the given store.

func (*Session) Clear

func (s *Session) Clear()

Clear removes all data from the session and marks it dirty.

func (*Session) CreatedAt

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

CreatedAt returns the session creation time.

func (*Session) Data

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

Data returns a copy of the session data map.

func (*Session) Delete

func (s *Session) Delete(key string)

Delete removes a key from the session and marks it dirty.

func (*Session) Destroy

func (s *Session) Destroy(ctx context.Context) error

Destroy deletes the session from its store.

func (*Session) Get

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

Get retrieves a value by key. Returns nil if the key does not exist.

func (*Session) GetInto

func (s *Session) GetInto(key string, target any) error

GetInto unmarshals a JSON-encoded session value into the target. Returns an error if the key does not exist or unmarshaling fails.

func (*Session) GetString

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

GetString retrieves a string value by key. Returns "" if the key does not exist or the value is not a string.

func (*Session) ID

func (s *Session) ID() string

ID returns the opaque session identifier.

func (*Session) IsDirty

func (s *Session) IsDirty() bool

IsDirty reports whether the session has unsaved changes.

func (*Session) Save

func (s *Session) Save(ctx context.Context) (string, error)

Save persists the session through its store and returns the opaque token. It takes a snapshot of the session data under the read lock, then saves the snapshot outside the lock. After saving, it reacquires the lock and clears the dirty flag only if the revision has not advanced (i.e., no concurrent mutations occurred during the save).

func (*Session) Set

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

Set stores a value by key and marks the session as dirty.

type Store

type Store interface {
	// Load retrieves a session by its opaque token.
	// Returns an error if the token is invalid, expired, or not found.
	Load(ctx context.Context, token string) (*Session, error)

	// Save persists a session and returns its opaque token.
	Save(ctx context.Context, s *Session) (string, error)

	// Delete removes a session by its opaque token.
	Delete(ctx context.Context, token string) error
}

Store is the persistence backend for sessions. The token is an opaque string that the framework adapter stores in a cookie. For CookieStore, the token contains the signed payload. For server-side stores, the token is a session ID.

Jump to

Keyboard shortcuts

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