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 proxy import ( "log"
Building a hardened Go reverse proxy
reverse-proxy
http
timeouts
Intermediate
7 steps
go
package middleware import ( "net/http"
A per-IP rate limiter middleware in Gin
rate-limiting
token-bucket
middleware
Intermediate
8 steps
go
package tsvio import ( "bufio"
Reading and writing TSV records in Go
parsing
io-streams
error-handling
Intermediate
10 steps
go
package config import ( "fmt"
Loading and saving YAML config in Go
yaml
struct-tags
defaults
Intermediate
8 steps
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 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.