Skip to main content

Overview

The xml 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 contextKey type 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)
Content Type Detection: The middleware accepts both 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.MarshalIndent with configurable indent and prefix

Response Flow

  1. Middleware checks Accept header for XML compatibility
  2. If AutoParse enabled, reads and caches request body
  3. Stores options in context for response functions
  4. Response functions retrieve options from context
  5. Marshal data with appropriate settings
  6. Set Content-Type header with charset
  7. 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: