go
32 lines · 5 steps
How Gin renders MsgPack responses
A custom Render implementation serializes any value to MessagePack and wires it into Gin's response pipeline.
Explained by
highlit
1package render
2
3import (
4 "net/http"
5
6 "github.com/vmihailenco/msgpack/v5"
7)
8
9var msgpackContentType = []string{"application/msgpack; charset=utf-8"}
10
11type MsgPack struct {
12 Data any
13}
14
15func (r MsgPack) Render(w http.ResponseWriter) error {
16 r.WriteContentType(w)
17
18 enc := msgpack.NewEncoder(w)
19 enc.SetCustomStructTag("json")
20 return enc.Encode(r.Data)
21}
22
23func (r MsgPack) WriteContentType(w http.ResponseWriter) {
24 header := w.Header()
25 if val := header["Content-Type"]; len(val) == 0 {
26 header["Content-Type"] = msgpackContentType
27 }
28}
29
30func MsgPackResponse(c *gin.Context, code int, obj any) {
31 c.Render(code, MsgPack{Data: obj})
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing Gin's Render interface lets you plug any serialization format into the framework's response machinery.
- 2Setting the Content-Type only when unset lets callers override the header without being clobbered.
- 3Reusing the JSON struct tags for MessagePack keeps one set of field annotations across formats.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-gin-renders-msgpack-responses-explained-go-a480/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.