go 55 lines · 7 steps

Per-plan export limits in Gin middleware

A Gin middleware that caps how many records a request can export based on the account's subscription tier.

Explained by highlit
1package middleware
2 
3import (
4 "net/http"
5 "strconv"
6 
7 "github.com/gin-gonic/gin"
8)
9 
10var planExportCaps = map[string]int{
11 "free": 100,
12 "pro": 5_000,
13 "enterprise": 50_000,
14}
15 
16const defaultExportLimit = 100
17 
18func EnforceExportLimit() gin.HandlerFunc {
19 return func(c *gin.Context) {
20 plan, ok := c.Get("account_plan")
21 if !ok {
22 c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
23 "error": "account plan not resolved",
24 })
25 return
26 }
27 
28 cap, known := planExportCaps[plan.(string)]
29 if !known {
30 cap = defaultExportLimit
31 }
32 
33 raw := c.DefaultQuery("limit", strconv.Itoa(defaultExportLimit))
34 limit, err := strconv.Atoi(raw)
35 if err != nil || limit < 1 {
36 c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
37 "error": "limit must be a positive integer",
38 })
39 return
40 }
41 
42 if limit > cap {
43 c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{
44 "error": "requested export size exceeds plan limit",
45 "limit": limit,
46 "max_limit": cap,
47 "plan": plan,
48 })
49 return
50 }
51 
52 c.Set("export_limit", limit)
53 c.Next()
54 }
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Middleware can enforce business rules by short-circuiting the request with AbortWithStatusJSON before handlers ever run.
  2. 2Looking up limits in a map with a sensible default keeps tier logic centralized and easy to extend.
  3. 3Validated values passed via the context let downstream handlers trust the input without re-checking it.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Per-plan export limits in Gin middleware — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code