Skip to main content

Overview

The msgpack middleware provides MessagePack content negotiation and serialization for efficient binary data transfer. Use it when you need:
  • Binary serialization
  • Reduced payload size
  • Faster parsing

Installation

Quick Start

Examples

Enable MessagePack

Explicit MessagePack Response

Parse MessagePack Request

Content Negotiation

API Reference

Functions

Content Types

Technical Details

Architecture

The msgpack middleware implements a lightweight MessagePack encoder/decoder without external dependencies. It consists of three main components:

Middleware Handler

  • Intercepts requests with MessagePack content types
  • Stores raw request body in context for later parsing
  • Supports configurable content types (default: application/msgpack, application/x-msgpack)

Encoder

  • Implements MessagePack binary format specification
  • Uses fixed-size optimizations for common value ranges
  • Supports fixint, int8/16/32/64, uint8/16/32/64 encoding
  • Handles fixstr, str8/16/32 for strings with automatic size selection
  • Encodes binary data with bin8/16/32 formats
  • Supports fixarray, array16/32 and fixmap, map16/32 structures

Decoder

  • Parses MessagePack binary format to Go values
  • Returns generic any types (string, int64, uint64, float32/64, []any, map[string]any)
  • Validates buffer boundaries to prevent out-of-bounds access
  • Handles all MessagePack type codes including fixint, negative fixint, and type-specific codes

Type Mappings

Error Handling

The middleware defines three error types:
  • ErrUnsupportedType: Returned when attempting to encode unsupported Go types
  • ErrInvalidFormat: Returned when decoding encounters invalid MessagePack data
  • ErrBufferTooSmall: Returned when the input buffer is insufficient for the declared data

Context Storage

The middleware stores the raw MessagePack request body in the request context using a private context key. This allows:
  • Multiple reads of the request body
  • Access via the Body() helper function
  • Preservation of the original request body for middleware chain

Best Practices

  • Use for internal APIs
  • Fall back to JSON for browsers
  • Consider client library support
  • Benchmark for your use case

Testing

Test Coverage

The msgpack middleware includes comprehensive test coverage for all functionality: