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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Struct tags let you declare parsing, defaults, and validation rules in one place instead of hand-writing checks.
- 2Cross-field constraints like gtefield and defaults keep invalid or missing input from ever reaching business logic.
- 3Converting page/per_page into offset/limit at the boundary keeps the service layer unaware of HTTP pagination semantics.
Related explainers
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
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/validating-query-params-with-gin-binding-tags-explained-go-c878/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.