Skip to main content

Overview

The favicon middleware serves favicon files efficiently, caching them in memory and handling HEAD requests properly. It prevents favicon requests from reaching your application routes. Use it when you need:
  • Serve favicon from memory
  • Prevent favicon 404 logs
  • Custom favicon handling

Installation

Quick Start

Configuration

Options

Examples

From File

From Embedded Data

Custom Cache Control

Disable Favicon

API Reference

Functions

Behavior

  • Caches favicon in memory after first read
  • Sets proper Content-Type (image/x-icon)
  • Handles both GET and HEAD requests
  • Only matches exact /favicon.ico path

Technical Details

Implementation

The favicon middleware implements efficient favicon serving with the following characteristics:
  1. Memory Caching: Favicon data is loaded once during middleware initialization and cached in memory for the lifetime of the application.
  2. Content Type Detection: Uses http.DetectContentType() to automatically detect the content type from the favicon data. Falls back to image/x-icon if detection returns application/octet-stream or text/plain.
  3. File System Support: Supports three data sources:
    • Direct file path using os.ReadFile
    • Embedded data using []byte
    • File system interface (fs.FS) for advanced use cases
  4. Request Handling:
    • Only processes requests matching the configured URL path (default: /favicon.ico)
    • Only handles GET and HEAD methods, passes other methods to next handler
    • Sets appropriate headers: Content-Type, Content-Length, and Cache-Control
    • HEAD requests return headers without body
  5. Special Behaviors:
    • Empty configuration (no data) returns HTTP 204 No Content
    • SVG middleware supports both /favicon.ico and /favicon.svg paths
    • Redirect middleware returns HTTP 301 Moved Permanently

Performance Considerations

  • Favicon is loaded once at startup (panic on file errors)
  • No disk I/O during request handling
  • Minimal memory allocation per request
  • Early path matching prevents unnecessary processing

Best Practices

  • Use embedded data for portable deployments
  • Set long cache duration for production
  • Place before other middleware to avoid unnecessary processing

Testing

The favicon middleware includes comprehensive test coverage for all features:
  • static - Static file serving
  • spa - Single Page Application
  • cache - Cache headers