Skip to main content

Overview

The embed middleware provides helpers for serving files from Go’s embedded filesystem (embed.FS), enabling single-binary deployments. Use it when you need:
  • Single binary deployment
  • Bundled static assets
  • Embedded templates

Installation

Quick Start

Examples

Serve Static Files

With Prefix

Multiple Embeds

SPA with Embed

API Reference

Functions

Build Considerations

Technical Details

Implementation Overview

The embed middleware provides a bridge between Go’s embed.FS and Mizu’s HTTP serving capabilities. It wraps the standard library’s http.FileServer with additional features like custom root directories, caching headers, and SPA routing.

Core Components

Filesystem Handling
  • Uses fs.FS interface for maximum flexibility
  • Supports fs.Sub to create subdirectory filesystems
  • Falls back to original filesystem if subdirectory doesn’t exist
  • Implements proper path cleaning and normalization
File Serving Strategy
  1. Cleans and normalizes the request path
  2. Attempts to open the requested file
  3. Falls back to index file for directory requests
  4. Delegates to NotFoundHandler or next middleware if file not found
  5. Uses http.FileServer for actual serving (handles range requests, content-type, etc.)
Cache Control
  • Optional MaxAge setting for Cache-Control headers
  • Custom itoa function to avoid allocations for header values
  • Headers set before delegating to file server
SPA Support
  • Custom NotFoundHandler that serves index.html for missing routes
  • Preserves normal file serving for actual assets
  • Uses http.ServeContent for proper handling of conditional requests

Handler vs Middleware

The package provides both middleware and handler functions:
  • Middleware (New, WithOptions, Static, etc.): Falls through to next handler if file not found
  • Handler (Handler, HandlerWithOptions): Directly serves files without fallthrough

Best Practices

  • Use for production deployments
  • Keep embedded files small
  • Use content hashing for cache busting
  • Test embedded files in CI

Testing

The embed middleware includes comprehensive test coverage for all functionality: