Skip to main content

Overview

The header middleware provides flexible request and response header manipulation. Add, modify, or remove headers for security, caching, or custom requirements.

Installation

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

Quick Start

app := mizu.New()

// Set response header
app.Use(header.Set("X-Powered-By", "Mizu"))

Functions

Response Headers

FunctionDescription
Set(key, value)Set response header
New(headers)Set multiple response headers
Remove(keys...)Remove response headers

Request Headers

FunctionDescription
SetRequest(key, value)Set request header
RemoveRequest(keys...)Remove request headers

Security Headers

FunctionHeader
XSSProtection()X-XSS-Protection
NoSniff()X-Content-Type-Options
FrameDeny()X-Frame-Options: DENY
FrameSameOrigin()X-Frame-Options: SAMEORIGIN
HSTS(maxAge, subdomains, preload)Strict-Transport-Security
CSP(policy)Content-Security-Policy
ReferrerPolicy(policy)Referrer-Policy
PermissionsPolicy(policy)Permissions-Policy

Content Headers

FunctionContent-Type
JSON()application/json
HTML()text/html
Text()text/plain
XML()application/xml

Examples

Set Single Header

app.Use(header.Set("X-Custom-Header", "value"))

Set Multiple Headers

app.Use(header.New(map[string]string{
    "X-App-Name":    "MyApp",
    "X-App-Version": "1.0.0",
}))

Remove Headers

// Remove sensitive headers
app.Use(header.Remove("Server", "X-Powered-By"))

Security Headers

app.Use(header.XSSProtection())
app.Use(header.NoSniff())
app.Use(header.FrameDeny())

HSTS

app.Use(header.HSTS(31536000, true, true)) // 1 year, subdomains, preload

Content Security Policy

app.Use(header.CSP("default-src 'self'; script-src 'self' cdn.example.com"))

Full Configuration

app.Use(header.WithOptions(header.Options{
    Response: map[string]string{
        "X-Frame-Options":        "DENY",
        "X-Content-Type-Options": "nosniff",
    },
    ResponseRemove: []string{"Server"},
    Request: map[string]string{
        "X-Request-Source": "web",
    },
}))

API Reference

func Set(key, value string) mizu.Middleware
func SetRequest(key, value string) mizu.Middleware
func New(headers map[string]string) mizu.Middleware
func Remove(keys ...string) mizu.Middleware
func RemoveRequest(keys ...string) mizu.Middleware
func WithOptions(opts Options) mizu.Middleware

Technical Details

Architecture

The header middleware is built on the WithOptions function, which serves as the core implementation. All other functions (Set, New, Remove, etc.) are convenience wrappers that delegate to WithOptions with specific configurations.

Options Structure

type Options struct {
    Request        map[string]string // Request headers to set
    Response       map[string]string // Response headers to set
    RequestRemove  []string          // Request headers to remove
    ResponseRemove []string          // Response headers to remove
}

Execution Flow

  1. Request Phase (before handler):
    • Sets request headers from Options.Request
    • Removes request headers from Options.RequestRemove
    • Sets response headers from Options.Response
  2. Handler Execution: Calls the next middleware/handler
  3. Response Phase (after handler):
    • Removes response headers from Options.ResponseRemove

Implementation Notes

  • Request headers are set before the handler executes, making them available to downstream handlers
  • Response headers are set before the handler but can be overridden by the handler
  • Response header removal happens after the handler executes to ensure headers set by the handler are properly removed
  • The middleware uses a custom itoa function for integer-to-string conversion to avoid unnecessary allocations in HSTS header generation

Best Practices

  • Use WithOptions for complex configurations involving multiple header operations
  • Use convenience functions (Set, Remove, etc.) for simple single-header operations
  • Set security headers at the application level rather than per-route
  • Remove sensitive headers (e.g., Server, X-Powered-By) to avoid information disclosure
  • Chain multiple header middlewares when you need different headers for different routes

Testing

The header middleware includes comprehensive test coverage for all functions:
Test CaseDescriptionExpected Behavior
TestNewTests setting multiple response headersHeaders X-Custom and X-Another are set in response
TestWithOptions_RequestHeadersTests setting request headersHeader X-Injected is available in request context
TestWithOptions_RemoveHeadersTests removing request and response headersRequest header X-Remove-Me and response header X-Server are removed
TestSetTests setting a single response headerHeader X-Test is set in response
TestSetRequestTests setting a single request headerHeader X-Request-Custom is available in request
TestRemoveTests removing multiple response headersHeaders Server and X-Powered-By are removed from response
TestRemoveRequestTests removing request headersHeader Cookie is removed from request
TestXSSProtectionTests XSS protection headerHeader X-XSS-Protection is set to 1; mode=block
TestNoSniffTests content type sniffing protectionHeader X-Content-Type-Options is set to nosniff
TestFrameDenyTests frame options denyHeader X-Frame-Options is set to DENY
TestFrameSameOriginTests frame options same originHeader X-Frame-Options is set to SAMEORIGIN
TestHSTSTests HTTP Strict Transport SecurityHeader Strict-Transport-Security is set with max-age, includeSubDomains, and preload
TestCSPTests Content Security PolicyHeader Content-Security-Policy is set with custom policy
TestReferrerPolicyTests referrer policyHeader Referrer-Policy is set to strict-origin
TestJSONTests JSON content typeHeader Content-Type is set to application/json; charset=utf-8
TestHTMLTests HTML content typeHeader Content-Type is set to text/html; charset=utf-8
TestTextTests text content typeHeader Content-Type is set to text/plain; charset=utf-8
TestXMLTests XML content typeHeader Content-Type is set to application/xml; charset=utf-8
  • helmet - Comprehensive security headers