go
58 lines · 8 steps
Custom query validation in Gin
Bind a search query in Gin, register a custom slice-length validator, and normalize incoming tags before validating.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5 "strings"
6
7 "github.com/gin-gonic/gin"
8 "github.com/gin-gonic/gin/binding"
9 "github.com/go-playground/validator/v10"
10)
11
12type SearchQuery struct {
13 Keyword string `form:"q"`
14 Tags []string `form:"tags" binding:"tagslice,dive,alphanum"`
15 Page int `form:"page,default=1" binding:"min=1"`
16}
17
18func RegisterTagValidators() {
19 v, ok := binding.Validator.Engine().(*validator.Validate)
20 if !ok {
21 return
22 }
23 v.RegisterValidation("tagslice", func(fl validator.FieldLevel) bool {
24 return fl.Field().Len() <= 10
25 })
26}
27
28func splitTags(raw []string) []string {
29 seen := make(map[string]struct{})
30 out := make([]string, 0, len(raw))
31 for _, chunk := range raw {
32 for _, part := range strings.Split(chunk, ",") {
33 part = strings.ToLower(strings.TrimSpace(part))
34 if part == "" {
35 continue
36 }
37 if _, dup := seen[part]; dup {
38 continue
39 }
40 seen[part] = struct{}{}
41 out = append(out, part)
42 }
43 }
44 return out
45}
46
47func SearchArticles(c *gin.Context) {
48 var q SearchQuery
49 q.Tags = splitTags(c.QueryArray("tags"))
50
51 if err := c.ShouldBindQuery(&q); err != nil {
52 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
53 return
54 }
55
56 articles := articleRepo.Search(c.Request.Context(), q.Keyword, q.Tags, q.Page)
57 c.JSON(http.StatusOK, gin.H{"data": articles, "tags": q.Tags})
58}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Gin exposes its underlying validator engine so you can register domain-specific rules by name.
- 2Struct tags let a single field chain multiple constraints like a custom rule plus per-element checks.
- 3Normalizing input before binding keeps validation logic focused on rules rather than cleanup.
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/custom-query-validation-in-gin-explained-go-ba39/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.