Overview
While JSON is the most common format for web APIs, binary serialization formats can provide significant performance and size benefits. Fiber supports multiple formats out of the box.MessagePack (MsgPack)
MessagePack is an efficient binary serialization format that’s like JSON but faster and smaller.Benefits
- 30-50% smaller than JSON
- Faster encoding/decoding
- Type preservation
- Wide language support
Setup
Fiber doesn’t bundle MsgPack (it’s not in Go’s standard library), so choose a library: Recommended Libraries:- vmihailenco/msgpack - Feature-rich, widely used
- shamaton/msgpack/v3 - High performance
Configuration
Basic Usage
Auto Format
Fiber can automatically choose MsgPack based on the Accept header:Using vmihailenco/msgpack
Alternative library with more features:CBOR (Concise Binary Object Representation)
CBOR is a binary format similar to MessagePack, defined in RFC 8949.Benefits
- Standardized (IETF RFC)
- Compact binary encoding
- Supports more data types than JSON
- Good for IoT and constrained environments
Setup
Configuration
Basic Usage
Auto Format with CBOR
XML Support
Fiber has built-in XML support using Go’s standard library:Custom XML Encoder
For better performance, use a custom XML library:Form Data Binding
Fiber supports form data with automatic binding:Multipart Form with Files
Content Negotiation
Fiber’sAutoFormat automatically selects the best format:
Format Comparison
Size Comparison
For a typical API response with 1000 users:| Format | Size | Compression |
|---|---|---|
| JSON | 85 KB | Baseline |
| JSON (minified) | 65 KB | 23% smaller |
| MessagePack | 48 KB | 43% smaller |
| CBOR | 52 KB | 39% smaller |
| Protobuf* | 35 KB | 59% smaller |
Performance Comparison
Benchmark results for encoding/decoding 1000 objects:| Format | Encode | Decode | Total |
|---|---|---|---|
| JSON (stdlib) | 2.5ms | 3.2ms | 5.7ms |
| JSON (goccy/go-json) | 0.9ms | 1.1ms | 2.0ms |
| MessagePack | 0.8ms | 1.0ms | 1.8ms |
| CBOR | 1.0ms | 1.2ms | 2.2ms |
When to Use What
JSON- Human-readable debugging needed
- Browser/JavaScript clients
- Wide compatibility required
- Simple data structures
- Performance is critical
- Network bandwidth is limited
- Server-to-server communication
- Mobile applications
- IoT/embedded systems
- Standards compliance required
- Complex data types needed
- Interoperability with other CBOR systems
- Legacy system integration
- SOAP services
- Complex document structures
- Schema validation required
Custom Serialization
Implement custom encoding for specialized formats:Best Practices
- Choose the right format - JSON for web, MsgPack for performance
- Document your API - Specify supported formats in docs
- Support multiple formats - Use
AutoFormatfor flexibility - Version your APIs - Format changes can break clients
- Benchmark your use case - Test with realistic data
- Consider compression - Gzip can reduce JSON size significantly
- Validate input - Always validate regardless of format