go 58 lines · 8 steps

Validating query params with Gin binding tags

A Gin handler declaratively parses, defaults, and validates a product listing's query string before touching the service layer.

Explained by highlit
1package handlers
2 
3import (
4 "net/http"
5 "time"
6 
7 "github.com/gin-gonic/gin"
8)
9 
10type ListProductsQuery struct {
11 Search string `form:"q"`
12 Category string `form:"category" binding:"omitempty,oneof=books toys food"`
13 MinPrice float64 `form:"min_price" binding:"omitempty,gte=0"`
14 MaxPrice float64 `form:"max_price" binding:"omitempty,gtefield=MinPrice"`
15 InStock *bool `form:"in_stock"`
16 CreatedAt time.Time `form:"created_after" time_format:"2006-01-02"`
17 SortBy string `form:"sort_by,default=created_at" binding:"oneof=created_at price name"`
18 Order string `form:"order,default=desc" binding:"oneof=asc desc"`
19 Page int `form:"page,default=1" binding:"min=1"`
20 PerPage int `form:"per_page,default=20" binding:"min=1,max=100"`
21}
22 
23func ListProducts(svc *ProductService) gin.HandlerFunc {
24 return func(c *gin.Context) {
25 var query ListProductsQuery
26 if err := c.ShouldBindQuery(&query); err != nil {
27 c.JSON(http.StatusBadRequest, gin.H{
28 "error": "invalid query parameters",
29 "details": err.Error(),
30 })
31 return
32 }
33 
34 products, total, err := svc.List(c.Request.Context(), ProductFilter{
35 Search: query.Search,
36 Category: query.Category,
37 MinPrice: query.MinPrice,
38 MaxPrice: query.MaxPrice,
39 InStock: query.InStock,
40 CreatedAfter: query.CreatedAt,
41 SortBy: query.SortBy,
42 Order: query.Order,
43 Offset: (query.Page - 1) * query.PerPage,
44 Limit: query.PerPage,
45 })
46 if err != nil {
47 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load products"})
48 return
49 }
50 
51 c.JSON(http.StatusOK, gin.H{
52 "data": products,
53 "page": query.Page,
54 "per_page": query.PerPage,
55 "total": total,
56 })
57 }
58}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Struct tags let you declare parsing, defaults, and validation rules in one place instead of hand-writing checks.
  2. 2Cross-field constraints like gtefield and defaults keep invalid or missing input from ever reaching business logic.
  3. 3Converting page/per_page into offset/limit at the boundary keeps the service layer unaware of HTTP pagination semantics.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating query params with Gin binding tags — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code