Overview
Theenvelope middleware wraps all responses in a consistent structure, adding metadata like status, pagination, and timestamps.
Use it when you need:
- Consistent API responses
- Response metadata
- Standardized error format
Installation
Quick Start
Configuration
Options
Examples
Default Envelope
With Metadata
Custom Structure
With Pagination
API Reference
Functions
Response Format
Success Response
Error Response
Technical Details
Implementation Architecture
The envelope middleware uses a custom response writer (envelopeWriter) to intercept and capture the original response before wrapping it in the envelope structure.
Response Writer
The middleware captures responses through a buffer-based writer:- Intercepts
WriteHeader()calls to capture HTTP status codes - Buffers response body through
Write()calls - Stores status code (defaults to 200 if not explicitly set)
Envelope Construction
The envelope is constructed after the handler completes:- Content-Type Check: Only wraps responses matching configured content types (default:
application/json) - Success Determination: Status codes 200-399 are considered successful
- Response Parsing: Original JSON response is unmarshaled into the data field
- Error Handling: For error responses, attempts to extract error message from:
errorfield in response bodymessagefield in response body- Handler error if available
- Metadata Addition: When
IncludeMetais enabled, adds status code and request ID - Re-encoding: Final envelope is marshaled to JSON and written to the original writer
Field Customization
All field names are customizable through options:SuccessField: Controls the success indicator field nameDataField: Controls the data payload field nameErrorField: Controls the error message field name
Content-Type Filtering
The middleware only wraps responses with matching content types:- Checks exact match or with charset suffix (e.g.,
application/json; charset=utf-8) - Non-matching responses pass through unmodified
- Default content types:
["application/json"]
Helper Functions
The package provides convenience functions for common responses:Success(): 200 OK with dataCreated(): 201 Created with dataNoContent(): 204 No ContentBadRequest(): 400 Bad Request with error messageUnauthorized(): 401 Unauthorized with error messageForbidden(): 403 Forbidden with error messageNotFound(): 404 Not Found with error messageInternalError(): 500 Internal Server Error with error message
Best Practices
- Use consistent structure across APIs
- Include relevant metadata
- Document envelope format
- Handle nested errors properly
Testing
The envelope middleware includes comprehensive tests covering all functionality:Related Middlewares
- transformer - Response transformation
- requestid - Request IDs
- errorpage - Error pages