http.handlers.headers
Overview
Changes to headers are applied immediately, except for response headers whendeferred is true or when require is set. In those cases, changes are applied when headers are written to the response.
Deferred changes do not take effect if an error occurs later in the middleware chain.
Configuration
Header operations to apply to the request.See Header Operations for available fields.
Header operations to apply to the response.See Header Operations for other available fields.
If set, header operations will only be performed if the response matches these criteria. This is a response matcher.
If true, header operations will be deferred until they are written out. Usually needed when deleting headers.Superseded if
require is set.Header Operations
Adds HTTP headers. Does not replace any existing header fields.
Sets HTTP headers, replacing existing header fields.
Names of HTTP header fields to delete. Basic wildcards are supported:
- Start with
*for all field names with the given suffix - End with
*for all field names with the given prefix - Start and end with
*for all field names containing a substring *alone deletes all headers
Performs in-situ substring replacements of HTTP headers.Keys are field names on which to perform the associated replacements. If the field name is
*, replacements are performed on all header fields.Each field name maps to an array of replacement operations.The substring to search for.
The regular expression to search with.
The string with which to replace matches.
Cannot specify both
search and search_regexp for the same replacement.Configuration Examples
Add Security Headers
Remove Server Headers
Add CORS Headers
Conditional Response Headers
Request Headers with Placeholders
Replace Header Values
Delete Headers by Pattern
Deferred Header Operations
Special Header Handling
Host Header
TheHost header is handled specially for requests:
r.Host directly, as the standard library does not include Host in the header map.
Multiple Values
Headers can have multiple values. When setting headers with multiple values:Cache-Control: public, max-age=3600
Regular Expression Support
Regular expressions in replacements support placeholders and are compiled at runtime if they contain placeholders:Response Matcher
When usingrequire, you can match on:
- status_code - Array of status codes or code classes (2xx, 3xx, etc.)
- headers - Header field matchers
Common Use Cases
Security Headers
Add comprehensive security headers:Caching Headers
API Gateway Headers
Header operations are performed in order: delete all (
*), add, set, delete (specific), replace. This ensures predictable behavior when combining multiple operations.