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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing Gin's Render interface lets you plug any serialization format into the framework's response machinery.
  2. 2Setting the Content-Type only when unset lets callers override the header without being clobbered.
  3. 3Reusing the JSON struct tags for MessagePack keeps one set of field annotations across formats.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How Gin renders MsgPack responses — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code