Overview
Thesession middleware provides server-side session management with secure cookie-based tracking. Sessions can store user data across requests with configurable storage backends.
Use it when you need:
- User login sessions
- Shopping cart persistence
- Multi-step form wizards
Installation
Quick Start
Configuration
Options
Examples
Basic Sessions
Secure Cookie Settings
Custom Store
Session Operations
Logout
API Reference
Functions
Session Methods
Store Interface
Technical Details
Session Lifecycle
The session middleware manages a complete lifecycle for each session:- Session Creation: When a new request arrives without a session cookie, a new session ID is generated using
crypto/rand(32 bytes, 64 hex characters) and stored in the context - Cookie Management: Session cookies are set before the handler executes to ensure headers are properly sent
- Data Persistence: Session data is saved to the store only when changes are detected via the
changedflag - Cleanup: The memory store includes automatic cleanup that runs every 10 minutes to remove sessions inactive for more than 24 hours
Thread Safety
The Session struct usessync.RWMutex for concurrent access:
- Read operations (
Get): Use read locks to allow multiple concurrent reads - Write operations (
Set,Delete,Clear,Destroy): Use write locks for exclusive access - The
changedflag tracks modifications to optimize store operations
Store Implementation
The package includes aMemoryStore implementation with:
- Deep copying:
Getreturns a deep copy of session data to prevent external mutations - Background cleanup: Automatic goroutine removes expired sessions every 10 minutes
- Concurrent safety: All operations are protected by
sync.RWMutex
Session ID Generation
Session IDs are generated using:Context Integration
Sessions are stored in the request context using a privatecontextKey{} struct, preventing collisions with other middleware or application code.
Security Considerations
- Use HTTPS - Always set
CookieSecure: truein production - HTTPOnly cookies - Keep default to prevent XSS access
- Strict SameSite - Use
SameSiteStrictModefor sensitive apps - Regenerate ID - After login to prevent session fixation
- Set expiration - Donβt use infinite sessions
Best Practices
- Use secure cookie settings in production
- Store minimal data in sessions
- Implement session store cleanup for expired sessions
- Consider Redis or database store for distributed systems