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 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/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.