go
45 lines · 7 steps
Safe query filtering in a Gin handler
A Gin handler parses filter[...] query params against a whitelist and turns them into safe, parameterized database conditions.
Explained by
highlit
1func ListProducts(c *gin.Context) {
2 allowed := map[string]string{
3 "category": "category",
4 "brand": "brand",
5 "status": "status",
6 }
7
8 filters := make(map[string]interface{})
9 for key, values := range c.Request.URL.Query() {
10 if !strings.HasPrefix(key, "filter[") || !strings.HasSuffix(key, "]") || len(values) == 0 {
11 continue
12 }
13
14 field := key[len("filter[") : len(key)-1]
15 column, ok := allowed[field]
16 if !ok {
17 c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("unknown filter %q", field)})
18 return
19 }
20
21 if len(values) > 1 {
22 filters[column] = values
23 } else {
24 filters[column] = values[0]
25 }
26 }
27
28 query := db.Model(&Product{})
29 for column, value := range filters {
30 switch v := value.(type) {
31 case []string:
32 query = query.Where(column+" IN ?", v)
33 default:
34 query = query.Where(column+" = ?", v)
35 }
36 }
37
38 var products []Product
39 if err := query.Find(&products).Error; err != nil {
40 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load products"})
41 return
42 }
43
44 c.JSON(http.StatusOK, gin.H{"data": products, "filters": filters})
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Whitelisting request fields to real column names is what keeps user input from reaching SQL unchecked.
- 2Parameterized Where clauses with ? placeholders defend against injection even when the column name comes from a fixed map.
- 3A type switch lets one filter map carry both single values and slices, mapping cleanly to = versus IN.
Related explainers
go
package middleware import ( "net/http"
Localized validation errors in Gin
middleware
internationalization
validation
Intermediate
8 steps
python
from flask import Blueprint, jsonify from marshmallow import Schema, fields, validate, EXCLUDE from webargs.flaskparser import use_args
Validating query params in Flask with webargs
validation
schema
query-building
Intermediate
10 steps
go
func (h *ExportHandler) BulkExport(c *gin.Context) { projectID := c.Param("projectID") reports, err := h.reports.ListByProject(c.Request.Context(), projectID)
Streaming a ZIP download in Gin
streaming
zip-archive
http-headers
Intermediate
8 steps
go
package middleware import ( "crypto/sha256"
Deduplicating concurrent requests in Gin
singleflight
request-coalescing
middleware
Advanced
8 steps
ruby
class SearchController < ApplicationController def index @query = params[:q].to_s.strip end
Live search suggestions in a Rails controller
controllers
sql-injection
query-building
Intermediate
6 steps
go
package health import ( "context"
Building a health check endpoint in Go
health-check
context-timeout
dependency-probing
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/safe-query-filtering-in-a-gin-handler-explained-go-d68c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.