Overview
Thexml middleware provides XML content negotiation, parsing, and response helpers for XML-based APIs.
Use it when you need:
- XML API endpoints
- SOAP compatibility
- Legacy system integration
Installation
Quick Start
Examples
XML Response
Parse XML Request
Content Negotiation
With Declaration
API Reference
Functions
Content Types
Technical Details
Architecture
The XML middleware uses a context-based architecture to store and retrieve XML-specific data:- Context Keys: Uses private
contextKeytype to store body data, options, and preferred format - Auto-Parsing: Optionally reads and caches XML request bodies for reusable access
- Content Negotiation: Detects client preferences via Accept header and stores format preference
Implementation Details
Middleware Options:Indent: Indentation string for pretty printing (default: empty)Prefix: Prefix for each XML element (default: empty)ContentType: Content type for responses (default: “application/xml”)AutoParse: Automatically parse XML request bodies (default: false)XMLDeclaration: Include XML declaration in responses (default: true)
application/xml and text/xml content types, as well as */* and empty Accept headers.
XML Declaration:
By default, all responses include the standard XML declaration (<?xml version="1.0" encoding="UTF-8"?>). This can be disabled via options.
Marshal Options:
- Standard marshaling: Uses
xml.Marshal - Pretty printing: Uses
xml.MarshalIndentwith configurable indent and prefix
Response Flow
- Middleware checks Accept header for XML compatibility
- If AutoParse enabled, reads and caches request body
- Stores options in context for response functions
- Response functions retrieve options from context
- Marshal data with appropriate settings
- Set Content-Type header with charset
- Write XML declaration (if enabled) and data
Best Practices
- Use proper struct tags
- Handle encoding correctly
- Validate XML input
- Consider namespace handling
- Enable AutoParse when binding XML requests frequently
- Use Pretty() middleware during development for readable output
Testing
The XML middleware includes comprehensive test coverage for all functionality:Related Middlewares
- contenttype - Content-Type validation
- msgpack - MessagePack handling
- validator - Input validation