go
45 lines · 6 steps
Header-driven API versioning in Gin
A Gin handler binds request headers to a struct and shapes its JSON response based on the client's requested API version.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5
6 "github.com/gin-gonic/gin"
7)
8
9type clientMeta struct {
10 APIVersion string `header:"X-Api-Version" binding:"required"`
11 Platform string `header:"X-Client-Platform"`
12 RequestID string `header:"X-Request-Id"`
13}
14
15func GetProfile(svc ProfileService) gin.HandlerFunc {
16 return func(c *gin.Context) {
17 var meta clientMeta
18 if err := c.ShouldBindHeader(&meta); err != nil {
19 c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
20 "error": "missing or invalid X-Api-Version header",
21 })
22 return
23 }
24
25 userID := c.Param("id")
26 profile, err := svc.Fetch(c.Request.Context(), userID)
27 if err != nil {
28 c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "profile not found"})
29 return
30 }
31
32 switch meta.APIVersion {
33 case "2024-10", "2024-06":
34 c.JSON(http.StatusOK, newProfileV2(profile))
35 case "2023-01":
36 c.JSON(http.StatusOK, newProfileV1(profile))
37 default:
38 c.JSON(http.StatusNotAcceptable, gin.H{
39 "error": "unsupported API version",
40 "requested": meta.APIVersion,
41 "supported": []string{"2024-10", "2024-06", "2023-01"},
42 })
43 }
44 }
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Binding headers into a tagged struct lets you validate required metadata in one call instead of reading each header by hand.
- 2Returning a closure that captures dependencies keeps handlers testable while fitting Gin's HandlerFunc signature.
- 3Switching on a version header lets one endpoint serve multiple response shapes without breaking older clients.
Related explainers
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 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/header-driven-api-versioning-in-gin-explained-go-708a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.