Skip to main content

Overview

The errorpage middleware provides custom error pages for HTTP error responses, replacing default error responses with branded pages. Use it when you need:
  • Custom 404 pages
  • Branded error pages
  • User-friendly error messages

Installation

import "github.com/go-mizu/mizu/middlewares/errorpage"

Quick Start

app := mizu.New()

app.Use(errorpage.New(errorpage.Options{
    404: errorpage.File("./errors/404.html"),
    500: errorpage.File("./errors/500.html"),
}))

Configuration

Options

Error code to handler mapping:
type Options map[int]Handler

Examples

HTML Files

app.Use(errorpage.New(errorpage.Options{
    404: errorpage.File("./errors/404.html"),
    500: errorpage.File("./errors/500.html"),
}))

Inline HTML

app.Use(errorpage.New(errorpage.Options{
    404: errorpage.HTML(`
        <html>
        <body>
            <h1>Page Not Found</h1>
            <p>The page you requested does not exist.</p>
        </body>
        </html>
    `),
}))

JSON Errors

app.Use(errorpage.New(errorpage.Options{
    404: errorpage.JSON(map[string]string{
        "error": "Resource not found",
        "code":  "NOT_FOUND",
    }),
}))

Custom Handler

app.Use(errorpage.New(errorpage.Options{
    404: func(c *mizu.Ctx) error {
        // Log the 404
        log.Printf("404: %s", c.Request().URL.Path)
        // Return custom response
        return c.HTML(404, custom404Page)
    },
}))

Catch All Errors

app.Use(errorpage.New(errorpage.Options{
    400: errorHandler,
    401: errorHandler,
    403: errorHandler,
    404: errorHandler,
    500: errorHandler,
}))

API Reference

Functions

// New creates error page middleware
func New(opts Options) mizu.Middleware

// Response helpers
func File(path string) Handler
func HTML(content string) Handler
func JSON(data any) Handler
func Template(tmpl *template.Template, data any) Handler

Technical Details

Implementation Overview

The errorpage middleware uses a response writer wrapper (statusWriter) to intercept HTTP status codes before they are sent to the client. This allows the middleware to:
  1. Capture Status Codes: Wraps the response writer to track status codes without immediately sending them
  2. Conditional Rendering: Only renders error pages for status codes >= 400 when no response body has been written
  3. Template Processing: Uses Go’s html/template package for rendering error pages with customizable templates
  4. Default Pages: Provides pre-configured error pages for common HTTP error codes (400, 401, 403, 404, 405, 500, 502, 503, 504)

Response Writer Wrapper

The statusWriter type intercepts WriteHeader() calls to delay status code propagation until after determining whether a custom error page should be shown:
type statusWriter struct {
    http.ResponseWriter
    status  int
    written bool
}
This wrapper ensures that:
  • Status codes are captured but not immediately sent
  • Error pages are only shown when the response body hasn’t been written
  • The middleware can distinguish between different error scenarios

Error Handling Flow

  1. Request enters middleware
  2. Response writer is wrapped with statusWriter
  3. Next handler is called
  4. If status code >= 400 and no body written:
    • Custom error handler is invoked (if configured)
    • Custom 404 handler is invoked for 404s (if configured)
    • Appropriate error page is rendered using templates
  5. Response is sent to client

Best Practices

  • Keep error pages simple and fast
  • Include navigation back to home
  • Log errors for monitoring
  • Use different pages for client vs server errors

Testing

The errorpage middleware includes comprehensive test coverage for all major functionality:
Test CaseDescriptionExpected Behavior
TestNewTests default error page renderingReturns 404 status and displays default “Not Found” page with error code
TestWithOptions_CustomPagesTests custom error page configurationRenders custom title “Oops!” and message for 404 errors
TestWithOptions_CustomTemplateTests custom HTML templateRenders error using custom template format “Error 500: …”
TestWithOptions_NotFoundHandlerTests custom 404 handlerReturns JSON response {"error":"not found"} instead of HTML
TestWithOptions_ErrorHandlerTests custom error handler for all errorsReturns “Custom error handler” text for any error status
TestWithOptions_SuccessDoesNotShowErrorPageVerifies successful responses bypass error pagesReturns “success” without error page interference
TestNotFoundTests NotFound() middleware functionReturns 404 status with “Not Found” text
TestCustomTests Custom() middleware with specific pagesRenders “Maintenance” page for 503 status
TestPage404Tests Page404 helper functionCreates page with code 404 and custom title/message
TestPage500Tests Page500 helper functionCreates page with code 500 and custom title/message
TestDefaultPagesValidates all default error pages existConfirms default pages for codes 400, 401, 403, 404, 405, 500, 502, 503, 504