Skip to main content

Overview

The lastmodified 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

  1. Handler sets Last-Modified
  2. Client receives Last-Modified header
  3. Next request includes If-Modified-Since
  4. If not modified, returns 304 Not Modified
  5. 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.ParseTime which supports multiple date formats
  • 304 Response: Returns Not Modified when If-Modified-Since >= Last-Modified

Implementation Features

  • Options Configuration: Options struct allows customization with TimeFunc and SkipPaths
  • Path Skipping: Can skip specific paths using the SkipPaths option
  • 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 time
  • Now(): 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:
  • etag - ETag generation
  • cache - Cache-Control headers
  • static - Static files