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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Binding a lightweight envelope first lets you route a request before committing to a full schema.
- 2ShouldBindBodyWith caches the raw body so you can safely bind it more than once.
- 3Distinct status codes — 400 for malformed, 422 for invalid, 500 for downstream failures — make failures legible to clients.
Related explainers
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
go
package middleware import ( "compress/gzip"
How gzip HTTP middleware works in Go
middleware
compression
object-pooling
Intermediate
7 steps
php
<?php namespace App\Experiments;
Weighted random selection in PHP
weighted-random
cumulative-sum
sampling
Intermediate
8 steps
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
go
package handlers type ListFilters struct { Status string `form:"status" binding:"omitempty,oneof=active archived all"`
Cross-field query validation in Gin
validation
struct-tags
query-binding
Intermediate
9 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/two-pass-json-dispatch-in-gin-explained-go-71c4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.