session

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session stores data for a visitor across HTTP requests.

The go.laravel.com/middleware.StartSession middleware loads a Session before your handler runs and persists changes afterward. Access the current visitor's session from the request:

r.Session().Put("locale", "fr")
locale, _ := r.Session().Value[string]("locale")

Session payloads are encoded as JSON, so values read back with Session.Get have their JSON types (numbers as float64, structs as maps). Use Session.Value to decode a value back into a concrete Go type.

Built-in Store implementations include MemoryStore, FileStore, and DatabaseStore.

Index

Constants

View Source
const DefaultBag = "default"

DefaultBag is the error bag name used when a form does not specify one.

View Source
const UserIDKey = "_auth.web.id"

UserIDKey is the session key where package auth stores the signed-in user's ID as a string. DatabaseStore records this value in the user_id column.

Variables

This section is empty.

Functions

func CreateTable

func CreateTable(ctx context.Context) error

CreateTable creates the sessions table used by the database session driver. Register it directly in database/migrations/migrations.go:

{Name: "2026_01_01_000000_create_sessions_table", Run: session.CreateTable}

The table name follows SESSION_TABLE when configured, defaulting to "sessions".

func NewID

func NewID() string

NewID returns a cryptographically random 40-character alphanumeric session ID.

func ValidID

func ValidID(id string) bool

ValidID reports whether id is a valid 40-character alphanumeric session ID.

Types

type DatabaseStore

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

DatabaseStore persists sessions in a SQL database table with the columns id, user_id, ip_address, user_agent, payload, and last_activity (a timestamp). Each write records the signed-in user's ID, IP address, and user agent from the latest request so you can inspect or revoke active devices per user. DatabaseStore implements Store, UserSessions, and GarbageCollector.

func NewDatabaseStore

func NewDatabaseStore(conn *db.DB, table string, lifetime time.Duration) *DatabaseStore

NewDatabaseStore returns a DatabaseStore backed by table (such as "sessions") on conn. It uses the primary so the next request sees changes made to the session. Sessions expire after being idle for lifetime.

func (*DatabaseStore) CollectGarbage

func (d *DatabaseStore) CollectGarbage(ctx context.Context) error

CollectGarbage deletes all session rows whose last_activity is older than the store's lifetime.

func (*DatabaseStore) Destroy

func (d *DatabaseStore) Destroy(ctx context.Context, id string) error

Destroy deletes the session row for id.

func (*DatabaseStore) DestroyOthers

func (d *DatabaseStore) DestroyOthers(ctx context.Context, userID, except string) error

DestroyOthers deletes every session row belonging to userID except the session with ID except.

func (*DatabaseStore) Read

func (d *DatabaseStore) Read(ctx context.Context, id string) ([]byte, error)

Read returns the payload for id, or nil, nil if no row exists or the session has expired.

func (*DatabaseStore) Write

func (d *DatabaseStore) Write(ctx context.Context, id string, payload []byte, write Write) error

Write saves payload and request metadata for id. When write.Existing is true, Write updates the row only if it still exists so a request overlapping a sign-out does not resurrect the session.

type FileStore

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

FileStore stores each session in a file named after its session ID. Locking is process-local, so each server process should use its own directory.

func NewFileStore

func NewFileStore(dir string, lifetime time.Duration) *FileStore

NewFileStore returns a FileStore that writes session files in dir, creating dir on the first write. Sessions expire after being idle for lifetime.

func (*FileStore) CollectGarbage

func (f *FileStore) CollectGarbage(ctx context.Context) error

CollectGarbage deletes session files in the store's directory that have been idle longer than the configured lifetime.

func (*FileStore) Destroy

func (f *FileStore) Destroy(_ context.Context, id string) error

Destroy deletes the session file for id. Missing files and invalid IDs return nil.

func (*FileStore) Read

func (f *FileStore) Read(ctx context.Context, id string) ([]byte, error)

Read returns the payload stored in the file for id, or nil, nil if id is invalid, the file does not exist, or the session has expired.

func (*FileStore) Write

func (f *FileStore) Write(ctx context.Context, id string, payload []byte, write Write) error

Write atomically writes payload to the session file for id. It returns an error if id is invalid or the filesystem write fails. If write.Existing is true and the file has been removed, Write leaves it deleted and returns nil.

type GarbageCollector

type GarbageCollector interface {
	CollectGarbage(ctx context.Context) error
}

GarbageCollector is an optional interface for a Store that requires periodic cleanup of expired sessions. go.laravel.com/middleware.StartSession invokes CollectGarbage on roughly one in fifty requests.

type MemoryStore

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

MemoryStore keeps sessions in process memory. Sessions are lost when the process exits, making MemoryStore suitable for tests and local development.

func NewMemoryStore

func NewMemoryStore(lifetime time.Duration) *MemoryStore

NewMemoryStore returns a MemoryStore whose sessions expire after being idle for lifetime.

func (*MemoryStore) CollectGarbage

func (m *MemoryStore) CollectGarbage(ctx context.Context) error

CollectGarbage removes all sessions that have been idle longer than the store's lifetime.

func (*MemoryStore) Destroy

func (m *MemoryStore) Destroy(_ context.Context, id string) error

Destroy removes the session stored under id.

func (*MemoryStore) Read

func (m *MemoryStore) Read(ctx context.Context, id string) ([]byte, error)

Read returns the payload stored under id, or nil, nil if the session is missing or expired.

func (*MemoryStore) Write

func (m *MemoryStore) Write(ctx context.Context, id string, payload []byte, write Write) error

Write stores payload under id. If write.Existing is true and the session was already destroyed, Write does nothing and returns nil.

type Session

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

Session holds one visitor's session data, flash values, and CSRF token. Keys support dot notation, so "cart.items" addresses the "items" key inside a nested "cart" map. A Session is safe for concurrent use.

func New

func New(id string, encoded []byte) *Session

New constructs a Session with id and the encoded payload produced by Session.Encode. If id does not pass ValidID, New replaces it with a fresh ID from NewID so a visitor cannot supply an arbitrary session ID. If encoded is nil or cannot be decoded, New starts an empty session with a fresh CSRF token.

func (*Session) AgeFlash

func (s *Session) AgeFlash()

AgeFlash removes flash data from the previous request and schedules the current request's flash data for removal on the next request. go.laravel.com/middleware.StartSession calls AgeFlash before saving the session.

func (*Session) All

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

All returns a deep copy of all session data.

func (*Session) DestroyOtherSessions

func (s *Session) DestroyOtherSessions(userID string)

DestroyOtherSessions schedules the Store to delete every other session belonging to userID when this request saves the session, such as after a password change. This takes effect only when the store implements UserSessions.

func (*Session) Destroyed

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

Destroyed returns the previous session IDs replaced by Session.Regenerate or Session.Invalidate during this request. go.laravel.com/middleware.StartSession deletes them from the Store.

func (*Session) Encode

func (s *Session) Encode() []byte

Encode serializes the session's payload (everything except its ID) to JSON for storage in a Store.

func (*Session) ErrorBags

func (s *Session) ErrorBags() map[string]validation.Errors

ErrorBags returns all flashed validation error bags keyed by bag name.

func (*Session) Errors

func (s *Session) Errors(bag string) validation.Errors

Errors returns the validation errors flashed by the previous request for bag. Pass "" for DefaultBag.

func (*Session) Exists

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

Exists reports whether key is present in the session, even if its value is nil.

func (*Session) Flash

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

Flash stores a JSON-cloned copy of value at key for the next request only. It panics if value cannot be marshaled to JSON.

func (*Session) FlashErrors

func (s *Session) FlashErrors(bag string, fields validation.Errors)

FlashErrors flashes validation errors for the next request while preserving field order. Pass bag to distinguish multiple forms on the same page, or "" to use DefaultBag. Other error bags flashed during the same request are preserved.

func (*Session) FlashInput

func (s *Session) FlashInput(input map[string]any)

FlashInput flashes form input for the next request so a form can repopulate what the visitor typed. Password fields (password, password_confirmation, current_password) at any nesting depth and top-level _form are excluded automatically.

func (*Session) Flush

func (s *Session) Flush()

Flush removes all data, flash entries, and the previous URL from the session while keeping its CSRF token so open browser forms still submit.

func (*Session) Forget

func (s *Session) Forget(keys ...string)

Forget removes each key in keys from the session.

func (*Session) Get

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

Get returns a deep copy of the value at key, or nil if key is absent.

func (*Session) Has

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

Has reports whether key is present and holds a non-nil value.

func (*Session) ID

func (s *Session) ID() string

ID returns the session's current ID.

func (*Session) Invalidate

func (s *Session) Invalidate()

Invalidate clears all session data and assigns a new session ID and CSRF token. Call Invalidate when a user signs out.

func (*Session) Keep

func (s *Session) Keep(keys ...string)

Keep preserves the specified flash keys for one more request.

func (*Session) Now

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

Now stores a JSON-cloned copy of value at key for the current request only. It panics if value cannot be marshaled to JSON.

func (*Session) OldInput

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

OldInput returns the value at key from the input flashed by the previous request, along with whether the key was present. An empty field submitted by the visitor is present with a nil value.

func (*Session) OthersDestroyed

func (s *Session) OthersDestroyed() string

OthersDestroyed returns the user ID passed to Session.DestroyOtherSessions, or "" if none was set. go.laravel.com/middleware.StartSession reads this when saving the session.

func (*Session) PreviousURL

func (s *Session) PreviousURL() string

PreviousURL returns the URL of the last page the visitor loaded, or "" if none has been recorded.

func (*Session) Pull

func (s *Session) Pull[T any](key string) (T, bool)

Pull reads the value at key, removes it from the session, and decodes it into T. It returns the zero value of T and false if key is missing, nil, or cannot be decoded into T.

func (*Session) Put

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

Put stores a JSON-cloned copy of value at key. It panics if value cannot be marshaled to JSON, such as a channel or function.

func (*Session) Reflash

func (s *Session) Reflash()

Reflash preserves all flash data from the previous request for one more request.

func (*Session) Regenerate

func (s *Session) Regenerate()

Regenerate assigns a new session ID and CSRF token while keeping the session's data. Call Regenerate when a user signs in to prevent session fixation attacks.

func (*Session) RegenerateToken

func (s *Session) RegenerateToken()

RegenerateToken replaces the session's CSRF token with a new random token.

func (*Session) SetPreviousURL

func (s *Session) SetPreviousURL(url string)

SetPreviousURL records url as the last page the visitor loaded.

func (*Session) Token

func (s *Session) Token() string

Token returns the session's CSRF token.

func (*Session) Value

func (s *Session) Value[T any](key string) (T, bool)

Value reads the value at key and decodes it into T. It returns the zero value of T and false if key is missing, nil, or cannot be decoded into T.

type Store

type Store interface {
	Read(ctx context.Context, id string) ([]byte, error)
	Write(ctx context.Context, id string, payload []byte, write Write) error
	Destroy(ctx context.Context, id string) error
}

Store persists encoded session payloads between requests. Built-in stores include MemoryStore, FileStore, and DatabaseStore; package redis provides a Redis store, and cookie sessions store payloads directly in the browser cookie.

Read returns nil, nil when no session exists for id or when the session has expired.

Write stores payload under id. When write.Existing is true, Read found the session at the start of the request, and a concurrent request (such as a sign-out) may have destroyed it in the meantime. In that case, Write must update the payload only if the session still exists so a destroyed session is not resurrected. When write.Existing is false, Write creates the session or replaces an expired entry.

Destroy deletes the session for id. Destroying a missing session returns nil.

type UserSessions

type UserSessions interface {
	DestroyOthers(ctx context.Context, userID, except string) error
}

UserSessions is an optional interface for a Store that indexes sessions by user ID so it can terminate a user's other sessions, such as after a password change.

type Write

type Write struct {
	// Existing reports whether the store held the session at the start of the
	// request. It is false for new sessions and after [Session.Regenerate].
	Existing bool
	// IP is the client's IP address as resolved by trusted proxies.
	IP string
	// UserAgent is the request's User-Agent header, truncated to 500
	// characters.
	UserAgent string
	// UserID is the signed-in user's ID stored at [UserIDKey], or "" for a
	// guest.
	UserID string
}

Write carries request metadata passed to Store.Write when saving a session.

Jump to

Keyboard shortcuts

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