Overview
Thelastmodified middleware handles Last-Modified headers and If-Modified-Since conditional requests for efficient caching.
Use it when you need:
- Date-based caching
- Conditional GET requests
- Bandwidth optimization
Installation
Quick Start
Examples
Set Last-Modified
Auto Last-Modified
Static Files
How It Works
- Handler sets Last-Modified
- Client receives Last-Modified header
- Next request includes If-Modified-Since
- If not modified, returns 304 Not Modified
- If modified, returns full response
API Reference
Functions
Technical Details
The middleware implementation follows HTTP RFC 7232 specifications for conditional requests:- Time Format: Uses HTTP-date format (RFC 5322) for Last-Modified headers
- Time Comparison: Truncates to seconds precision for accurate comparison
- Method Filtering: Only processes GET and HEAD requests
- Header Parsing: Uses
http.ParseTimewhich supports multiple date formats - 304 Response: Returns Not Modified when If-Modified-Since >= Last-Modified
Implementation Features
- Options Configuration:
Optionsstruct allows customization withTimeFuncandSkipPaths - Path Skipping: Can skip specific paths using the
SkipPathsoption - Zero Time Handling: Skips middleware processing when time function returns zero time
- UTC Normalization: Automatically converts times to UTC before setting headers
Helper Functions
Static(t time.Time): Creates middleware with a fixed modification timeNow(): Uses current time for each request (useful for development/testing)StartupTime(): Uses application startup time (useful for versioned assets)FromHeader(header string): Reads modification time from a custom request header
Best Practices
- Use with ETag for robust caching
- Set accurate modification times
- Use for static and semi-static content
- Combine with Cache-Control
Testing
The middleware includes comprehensive test coverage for various scenarios:| Test Case | Description | Expected Behavior |
|---|---|---|
| TestNew | Basic middleware initialization | Sets Last-Modified header on response |
| TestIfModifiedSince_NotModified | Request with matching If-Modified-Since | Returns 304 Not Modified status |
| TestIfModifiedSince_Modified | Request with older If-Modified-Since | Returns 200 OK with full response |
| TestWithOptions_SkipPaths | Path configured to be skipped | No Last-Modified header set |
| TestSkipPostMethod | POST request to endpoint | No Last-Modified header (only GET/HEAD) |
| TestStatic | Static time middleware | Returns fixed Last-Modified time |
| TestNow | Current time middleware | Sets Last-Modified to current time |
| TestStartupTime | Startup time middleware | Consistent time across multiple requests |
| TestFromHeader | Custom header as time source | Reads and sets time from X-Resource-Modified |
| TestZeroTime | Time function returns zero value | No Last-Modified header set |