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 security import ( "crypto/hmac"
Signing and verifying payloads with HMAC in Go
hmac
cryptography
authentication
Intermediate
5 steps
go
package handlers import ( "context"
Liveness vs readiness health checks in Gin
health-checks
dependency-injection
context-timeout
Intermediate
7 steps
go
package storage import ( "context"
A SQLite-backed order store in Go
database/sql
sqlite
error-wrapping
Intermediate
7 steps
go
package auth import ( "errors"
Hashing and verifying passwords with bcrypt in Go
password-hashing
bcrypt
error-handling
Intermediate
7 steps
go
package fsutil import ( "io/fs"
Walking a directory tree to find large files in Go
filesystem
recursion
closures
Intermediate
7 steps
rust
use axum::{ extract::State, http::StatusCode, Json,
Idempotent webhook handling in Axum
deduplication
idempotency
shared-state
Intermediate
8 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.