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
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 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
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
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/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.