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
| Option | Type | Default | Description |
|---|---|---|---|
CookieName | string | "session_id" | Session cookie name |
CookiePath | string | "/" | Cookie path |
CookieDomain | string | "" | Cookie domain |
CookieSecure | bool | false | HTTPS only |
CookieHTTPOnly | bool | true | HTTP only (no JS access) |
SameSite | http.SameSite | Lax | SameSite policy |
MaxAge | time.Duration | 24h | Session lifetime |
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
Testing
The session middleware includes comprehensive test coverage for all operations:| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Set and get session value | Session values persist across requests with the same session cookie |
TestSession_Clear | Clear all session values | All session values are removed after calling Clear() |
TestSession_Delete | Delete specific session value | Individual session value is removed after calling Delete(key) |
TestWithStore | Custom store integration | Session middleware works with custom Store implementations |
TestSession_CustomCookie | Custom cookie configuration | Cookie settings (name, path, secure, SameSite) are applied correctly |
TestFromContext | Context retrieval alias | Get() and FromContext() return the same session instance |
TestGenerateSessionID | Session ID generation | Generates unique 64-character hex IDs without duplicates |