custom_middleware

command
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 23, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

Custom Middleware Example

This example demonstrates how to create custom middleware for the httpserver package.

What It Shows

  • Creating a custom middleware that transforms HTTP responses
  • Using built-in middleware from the httpserver package
  • Correct middleware ordering and composition
  • Separation of concerns between middleware layers

Key Components

JSON Enforcer Middleware

A custom middleware that ensures all responses are JSON formatted. Non-JSON responses are wrapped in {"response": "content"} while valid JSON passes through unchanged.

Headers Middleware

Uses the built-in headers middleware to set Content-Type, CORS, and security headers.

Running the Example

go run ./examples/custom_middleware

The server starts on :8081 with several endpoints to demonstrate the middleware behavior.

Endpoints

  • GET / - Returns plain text (wrapped in JSON)
  • GET /api/data - Returns JSON (preserved as-is)
  • GET /html - Returns HTML (wrapped in JSON)
  • GET /error - Returns 404 error (wrapped in JSON)
  • GET /panic - Triggers panic recovery middleware

Middleware Ordering

The example demonstrates why middleware order matters:

  1. Recovery - Must be first to catch panics
  2. Security - Set security headers early
  3. Logging - Log all requests
  4. Metrics - Collect request metrics
  5. Headers - Set response headers before handler

See the code comments in main.go.

Documentation

Overview

Package main demonstrates a JSON API server using go-supervisor with proper middleware layering and separation of concerns.

Middleware Architecture

This example shows how to properly layer middleware with clean separation of concerns:

1. JSON Enforcer Middleware (examples/jsonapi/middleware):

  • Only transforms response body content to JSON format
  • Does NOT set any headers
  • Wraps non-JSON responses in {"response": "content"}
  • Preserves valid JSON responses as-is

2. Headers Middleware (runnables/httpserver/middleware/headers):

  • Exclusively handles all HTTP header management
  • Sets Content-Type, CORS, security headers, etc.
  • Can be overridden by handlers if needed

3. Middleware Execution Order:

  • Request flow: recovery -> security -> logging -> metrics -> headers -> handler
  • Response flow: handler -> headers -> metrics -> logging -> security -> recovery
  • Order is critical: recovery must be outermost, headers should be innermost

This separation ensures each middleware has a single responsibility and they compose cleanly without conflicts.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL