go 60 lines · 8 steps

Two-pass JSON dispatch in Gin

A single endpoint peeks at an event's type, then re-binds the same body into the matching typed struct.

Explained by highlit
1package events
2 
3import (
4 "net/http"
5 
6 "github.com/gin-gonic/gin"
7 "github.com/gin-gonic/gin/binding"
8)
9 
10type envelope struct {
11 Type string `json:"type" binding:"required"`
12}
13 
14type paymentEvent struct {
15 Type string `json:"type"`
16 Amount int64 `json:"amount" binding:"required,gt=0"`
17 Currency string `json:"currency" binding:"required,len=3"`
18}
19 
20type refundEvent struct {
21 Type string `json:"type"`
22 ChargeID string `json:"charge_id" binding:"required"`
23 Reason string `json:"reason" binding:"required"`
24}
25 
26func (h *Handler) Ingest(c *gin.Context) {
27 var env envelope
28 if err := c.ShouldBindBodyWith(&env, binding.JSON); err != nil {
29 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
30 return
31 }
32 
33 switch env.Type {
34 case "payment":
35 var p paymentEvent
36 if err := c.ShouldBindBodyWith(&p, binding.JSON); err != nil {
37 c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
38 return
39 }
40 if err := h.svc.RecordPayment(c.Request.Context(), p.Amount, p.Currency); err != nil {
41 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to record payment"})
42 return
43 }
44 case "refund":
45 var r refundEvent
46 if err := c.ShouldBindBodyWith(&r, binding.JSON); err != nil {
47 c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
48 return
49 }
50 if err := h.svc.RecordRefund(c.Request.Context(), r.ChargeID, r.Reason); err != nil {
51 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to record refund"})
52 return
53 }
54 default:
55 c.JSON(http.StatusBadRequest, gin.H{"error": "unknown event type: " + env.Type})
56 return
57 }
58 
59 c.JSON(http.StatusAccepted, gin.H{"status": "accepted"})
60}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Binding a lightweight envelope first lets you route a request before committing to a full schema.
  2. 2ShouldBindBodyWith caches the raw body so you can safely bind it more than once.
  3. 3Distinct status codes — 400 for malformed, 422 for invalid, 500 for downstream failures — make failures legible to clients.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Two-pass JSON dispatch in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code