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

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

Quick Start

app := mizu.New()

app.Use(xml.New())

app.Get("/data", func(c *mizu.Ctx) error {
    return xml.Send(c, 200, data)
})

Examples

XML Response

type User struct {
    XMLName xml.Name `xml:"user"`
    ID      string   `xml:"id"`
    Name    string   `xml:"name"`
}

app.Get("/user/:id", func(c *mizu.Ctx) error {
    user := getUser(c.Param("id"))
    return xml.Send(c, 200, user)
})
// <user><id>1</id><name>John</name></user>

Parse XML Request

app.Post("/users", func(c *mizu.Ctx) error {
    var user User
    if err := xml.Bind(c, &user); err != nil {
        return err
    }
    // Process user
    return c.NoContent()
})

Content Negotiation

app.Use(xml.New())

app.Get("/data", func(c *mizu.Ctx) error {
    // Returns XML if Accept: application/xml
    // Returns JSON if Accept: application/json
    return c.Negotiate(200, data)
})

With Declaration

app.Get("/data", func(c *mizu.Ctx) error {
    return xml.SendWithDeclaration(c, 200, data)
})
// <?xml version="1.0" encoding="UTF-8"?><data>...</data>

API Reference

Functions

// New creates XML middleware
func New() mizu.Middleware

// Send sends XML response
func Send(c *mizu.Ctx, status int, data any) error

// SendWithDeclaration sends XML with declaration
func SendWithDeclaration(c *mizu.Ctx, status int, data any) error

// Bind parses XML request body
func Bind(c *mizu.Ctx, v any) error

Content Types

TypeDescription
application/xmlStandard XML
text/xmlAlternative

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:
Test CaseDescriptionExpected Behavior
TestNewBasic middleware initializationMiddleware should initialize and pass through requests successfully
TestResponseXML response generationShould return XML response with correct Content-Type header and proper XML structure
TestBindXML request body parsingShould parse XML request body into Go struct with AutoParse enabled
TestBodyRaw body retrievalShould retrieve cached XML body when AutoParse is enabled
TestSendErrorXML error responseShould send properly formatted XML error with code and message elements
TestPrettyPretty printingShould format XML with newlines and indentation when Pretty middleware is used
TestContentNegotiationContent negotiation based on Accept headerShould detect preferred format (XML/JSON) from Accept header, defaulting to JSON
TestRespondFormat-aware responseShould respond with XML or JSON based on content negotiation preference
TestXMLDeclarationXML declaration controlShould include/exclude XML declaration based on XMLDeclaration option
TestWrapXML wrapper elementShould wrap data in named root element correctly