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
- func GetTyped[T any](s *Session, key string) (T, error)
- func Middleware(manager *Manager, cookieName string) func(next func(*v2wf.RequestContext) error) func(*v2wf.RequestContext) error
- func MiddlewareWithConfig(cfg MiddlewareConfig) func(next func(*v2wf.RequestContext) error) func(*v2wf.RequestContext) error
- func SaveFlashToSession(s *Session, f *Flash)
- func SetTyped[T any](s *Session, key string, value T)
- type CookieStore
- type CookieStoreConfig
- type Flash
- func (f *Flash) ActiveEntries() map[string]string
- func (f *Flash) Add(key, value string)
- func (f *Flash) Clear()
- func (f *Flash) ConsumedEntries() []string
- func (f *Flash) Get(key string) string
- func (f *Flash) GetAll() map[string]string
- func (f *Flash) Has(key string) bool
- func (f *Flash) Peek(key string) string
- type Manager
- func (m *Manager) ExpireCookie(cookieName string) *http.Cookie
- func (m *Manager) LoadFromCookie(ctx context.Context, cookieName, cookieValue string) (*Session, *Flash, error)
- func (m *Manager) SaveToCookie(ctx context.Context, sess *Session, flash *Flash, cookieName string) (*http.Cookie, error)
- func (m *Manager) Store() Store
- type MiddlewareConfig
- type NoOpStore
- type SaveFailureMode
- type Session
- func (s *Session) Clear()
- func (s *Session) CreatedAt() time.Time
- func (s *Session) Data() map[string]any
- func (s *Session) Delete(key string)
- func (s *Session) Destroy(ctx context.Context) error
- func (s *Session) Get(key string) any
- func (s *Session) GetInto(key string, target any) error
- func (s *Session) GetString(key string) string
- func (s *Session) ID() string
- func (s *Session) IsDirty() bool
- func (s *Session) Save(ctx context.Context) (string, error)
- func (s *Session) Set(key string, value any)
- type Store
Constants ¶
const FlashKey = "_v2_flash"
FlashKey is the local storage key for the *Flash on the request parser.
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 ¶
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 ¶
SaveFlashToSession stores active (unconsumed) flash entries into a session.
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.
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 ¶
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 (*Flash) ActiveEntries ¶
ActiveEntries returns the flash entries that have not been consumed.
func (*Flash) ConsumedEntries ¶
ConsumedEntries returns the keys that have been read and should be removed on the next save cycle.
func (*Flash) Get ¶
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 ¶
GetAll returns all unconsumed flash entries and marks them as read (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 ¶
NewManager creates a session Manager backed by the given Store.
func (*Manager) ExpireCookie ¶
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).
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.
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 ¶
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) GetInto ¶
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 ¶
GetString retrieves a string value by key. Returns "" if the key does not exist or the value is not a string.
func (*Session) Save ¶
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).
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.