Gin and your data · 6 MIN READ

Gin list filters to parameterized SQL: parse strictly, bound IN lists, escape LIKE, end with a tiebreaker

Write a pure function that turns a Gin list request into SQL text and arguments, with allow-listed sorts, a placeholder for every value, escaped LIKE patterns, bounded IN lists and a unique tiebreaker.

List endpoints accumulate filters one release at a time: a status here, a search box there, a second sort key for the dashboard. Each one is a chance to splice a value into SQL text, to let a percent sign widen a search, or to send IN () to the database. Build the query in one function that owns every placeholder, and test that function without a database.

gin · A MAP OF THE IDEA

  1. Parse RawQuery strictly
  2. Validate, sort, dedupe
  3. Bind every value
  4. Order by constants + id

Useful when

  • The whole query is a pure function that table tests can pin exactly.
  • Equivalent requests produce identical SQL and arguments.

Watch out

  • Each IN list length is a new statement text; prefer = ANY($n) on PostgreSQL.
  • Leading-wildcard LIKE cannot use a B-tree index, however well it is escaped.

Implementation & operation cost: A builder type, explicit validation for every parameter and an index for each allowed sort combination.

01

One function between url.Values and QueryContext

The security.sql-injection lesson explains why statement text and values must reach the driver separately, and the pagination-filtering lesson covers cursors and why sort names go through an allow-list. What remains is the code in between: a function that takes the parsed query string plus the scope from the path or the authenticated principal and returns SQL text and an argument slice. Keeping it free of *gin.Context makes it a pure function, so a table test can assert the exact statement for each request. Keeping every filter in it gives a reviewer one place to check the invariant that matters: SQL text is assembled only from constants your code owns and placeholder numbers the builder generates.

02

Parse the raw query strictly, then canonicalize

c.Query, c.QueryArray and c.ShouldBindQuery all read c.Request.URL.Query(), which ignores the error from url.ParseQuery and keeps only the pairs it could parse. Since Go 1.17 a semicolon is not a separator, so ?status=open;closed loses its only pair and the client silently receives every status. Current Go releases also refuse a query with more than 10,000 pairs as a whole, controlled by the urlmaxqueryparams GODEBUG setting, so the handler sees no parameters at all. Parse c.Request.URL.RawQuery with url.ParseQuery yourself and answer 400 on error, then reject unknown names. Accept lists both as repeated keys and as comma-separated values, validate every element, and only then sort and dedupe. Canonical input means that equivalent requests produce byte-identical SQL and arguments, which keeps statement caches and query statistics small and lets a response cache keyed by the query reuse entries. The project scope comes from the path and is added first and unconditionally; it is not a filter the client may drop.

03

Build the statement and print it

buildQuery validates each parameter, adds a predicate per filter through a builder whose bind method is the only way to add a value, then appends the allow-listed ORDER BY, the tiebreaker and a bound LIMIT. The handler returns the SQL and arguments as text so the output shows exactly what a driver would receive. No database is involved.

go
package main

import (
	"cmp"
	"errors"
	"fmt"
	"maps"
	"net/http"
	"net/http/httptest"
	"net/url"
	"slices"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/gin-gonic/gin"
)

// sortable maps a public sort key to a column. Only these strings reach SQL.
var sortable = map[string]struct {
	column   string
	nullable bool
}{
	"created":  {column: "created_at"},
	"priority": {column: "priority"},
	"due":      {column: "due_at", nullable: true},
}

var statuses = []string{"closed", "open", "triaged"}

var allowedParams = []string{"assignee", "created_after", "limit", "q", "sort", "status"}

const maxAssignees = 20

// likeEscaper makes %, _ and the escape character literal inside a pattern.
var likeEscaper = strings.NewReplacer("!", "!!", "%", "!%", "_", "!_")

// builder collects predicates and arguments; bind is the only way to add a value.
type builder struct {
	where []string
	args  []any
}

func (b *builder) bind(v any) string {
	b.args = append(b.args, v)
	return "$" + strconv.Itoa(len(b.args))
}

func (b *builder) in(column string, values []any) {
	ph := make([]string, len(values))
	for i, v := range values {
		ph[i] = b.bind(v)
	}
	b.where = append(b.where, column+" IN ("+strings.Join(ph, ", ")+")")
}

// list accepts both ?status=a&status=b and ?status=a,b.
func list(values []string) []string {
	var out []string
	for _, v := range values {
		out = append(out, strings.Split(v, ",")...)
	}
	return out
}

// canonical sorts and dedupes, so equivalent requests produce the same SQL
// text and the same arguments.
func canonical[T cmp.Ordered](values []T) []any {
	slices.Sort(values)
	values = slices.Compact(values)
	out := make([]any, len(values))
	for i, v := range values {
		out[i] = v
	}
	return out
}

func buildQuery(projectID int64, q url.Values) (string, []any, error) {
	for _, name := range slices.Sorted(maps.Keys(q)) { // sorted: the same error every time
		if !slices.Contains(allowedParams, name) {
			return "", nil, fmt.Errorf("unknown parameter %q", name)
		}
	}
	b := &builder{}
	b.where = append(b.where, "project_id = "+b.bind(projectID)) // scope first, from the path

	if values := list(q["status"]); len(values) > 0 {
		for _, s := range values {
			if !slices.Contains(statuses, s) {
				return "", nil, fmt.Errorf("status %q is not one of %v", s, statuses)
			}
		}
		b.in("status", canonical(values))
	}
	if values := list(q["assignee"]); len(values) > 0 {
		if len(values) > maxAssignees { // bound the raw input before any work
			return "", nil, fmt.Errorf("at most %d assignees", maxAssignees)
		}
		ids := make([]int64, len(values))
		for i, s := range values {
			id, err := strconv.ParseInt(s, 10, 64)
			if err != nil || id <= 0 {
				return "", nil, fmt.Errorf("assignee %q is not a positive ID", s)
			}
			ids[i] = id
		}
		b.in("assignee_id", canonical(ids))
	}
	if text := strings.TrimSpace(q.Get("q")); text != "" {
		if utf8.RuneCountInString(text) > 100 {
			return "", nil, errors.New("q is longer than 100 characters")
		}
		pattern := "%" + likeEscaper.Replace(text) + "%"
		b.where = append(b.where, "title ILIKE "+b.bind(pattern)+" ESCAPE '!'")
	}
	if raw := q.Get("created_after"); raw != "" {
		t, err := time.Parse(time.RFC3339, raw)
		if err != nil {
			return "", nil, errors.New("created_after must be RFC 3339")
		}
		b.where = append(b.where, "created_at > "+b.bind(t.UTC()))
	}

	var order []string
	seen := map[string]bool{}
	for key := range strings.SplitSeq(q.Get("sort"), ",") {
		if key == "" {
			continue
		}
		dir, name := "ASC", key
		if rest, ok := strings.CutPrefix(key, "-"); ok {
			dir, name = "DESC", rest
		}
		col, ok := sortable[name]
		if !ok || seen[name] || len(seen) == 3 {
			return "", nil, fmt.Errorf("bad sort key %q", key)
		}
		seen[name] = true
		term := col.column + " " + dir
		if col.nullable {
			term += " NULLS LAST" // the same place for NULL in both directions
		}
		order = append(order, term)
	}
	if len(order) == 0 {
		order = append(order, "created_at DESC")
	}
	order = append(order, "id ASC") // unique tiebreaker: a total, repeatable order

	limit := 25
	if raw := q.Get("limit"); raw != "" {
		n, err := strconv.Atoi(raw)
		if err != nil || n < 1 || n > 100 {
			return "", nil, errors.New("limit must be 1..100")
		}
		limit = n
	}
	sql := "SELECT id, title, status, priority FROM issues WHERE " + strings.Join(b.where, " AND ") +
		" ORDER BY " + strings.Join(order, ", ") + " LIMIT " + b.bind(limit)
	return sql, b.args, nil
}

func formatArgs(args []any) string {
	parts := make([]string, len(args))
	for i, a := range args {
		switch v := a.(type) {
		case string:
			parts[i] = strconv.Quote(v)
		case time.Time:
			parts[i] = v.Format(time.RFC3339)
		default:
			parts[i] = fmt.Sprint(v)
		}
	}
	return "[" + strings.Join(parts, " ") + "]"
}

func main() {
	gin.SetMode(gin.TestMode)
	r := gin.New()
	r.GET("/projects/:project/issues", func(c *gin.Context) {
		projectID, err := strconv.ParseInt(c.Param("project"), 10, 64)
		if err != nil || projectID <= 0 {
			c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "no such project"})
			return
		}
		query, err := url.ParseQuery(c.Request.URL.RawQuery) // strict: c.Request.URL.Query drops errors
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "malformed query string"})
			return
		}
		sql, args, err := buildQuery(projectID, query)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		c.String(http.StatusOK, "%s\n  args: %s", sql, formatArgs(args))
	})

	for _, target := range []string{
		"/projects/7/issues",
		"/projects/7/issues?status=triaged,open&assignee=42&assignee=9,42&q=100%25_done&sort=-priority,due",
		"/projects/7/issues?status=open&status=triaged&created_after=2026-11-01T09:00:00%2B02:00&limit=50",
		"/projects/7/issues?sort=created%3BDROP+TABLE+issues",
		"/projects/7/issues?status=open;closed",
		"/projects/7/issues?status=open&status=archived",
		"/projects/7/issues?sort=priority,-priority",
		"/projects/7/issues?state=open",
	} {
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))
		fmt.Printf("GET %s\n  %d %s\n", target, w.Code, w.Body.String())
	}
}
Read the code

bind appends the value and returns its placeholder, so numbering follows argument order across WHERE, ORDER BY and LIMIT. In the second request triaged,open becomes the sorted pair open, triaged, and the assignee list 42, 9, 42 becomes 9 and 42 after parsing as integers; the raw count is bounded before any parsing. q=100%25_done decodes to 100%_done, and the escaper turns it into the pattern %100!%!_done%, matched literally under ESCAPE '!'; ILIKE is PostgreSQL's case-insensitive LIKE. created_after is parsed as RFC 3339 and passed as a UTC time.Time, never as text. A sort key containing an encoded semicolon is simply not in the map. An unencoded semicolon makes url.ParseQuery fail, which is a 400 here and would have been a missing filter with c.QueryArray. Unknown names are checked in sorted order so the error is deterministic.

04

Lists and patterns are where bound values still go wrong

A placeholder stops injection; it does not make a value mean what the user intended. LIKE treats % and _ in the bound value as wildcards, so escape them and name the escape character in the statement, as the security lesson shows, and cap the length. A pattern with a leading % cannot use an ordinary B-tree index, so contains-search over a large table needs a trigram index or full-text search, not a bigger timeout. IN lists need three guards: bound the raw count before doing work, refuse empty elements, and never emit IN (), which is a syntax error. Every distinct list length is also a distinct statement text, which multiplies prepared statements and plan-cache entries. PostgreSQL can take the whole list as one array argument instead.

go
// One placeholder per element: the statement text changes with the count.
//   status IN ($2, $3)
// One array argument: the statement text is the same for 1 or 20 values.
//   status = ANY($2)
func (b *builder) anyOf(column string, values any) {
	b.where = append(b.where, column+" = ANY("+b.bind(values)+")")
}

// With pgx, a []string or []int64 argument is sent as a PostgreSQL array.
// With lib/pq, wrap it: b.anyOf("assignee_id", pq.Array(ids)).
b.anyOf("assignee_id", ids)
Read the code

This fragment extends the program's builder for PostgreSQL; run it against a real driver in your own environment. = ANY($2) compares the column with each element of one array parameter, so the statement text stays constant whatever the list length, and the bound on the list still applies because it limits the work and the size of the argument. pgx encodes Go slices as PostgreSQL arrays directly, while lib/pq needs the pq.Array wrapper. Keep the canonical sort and dedupe so equal requests still send equal arguments.

05

Sort keys, directions and the tiebreaker

The client chooses among names; the server owns the SQL. A leading minus selects DESC, and the column, direction and NULL placement all come from constants. Refuse a repeated key and cap the number of keys, because every allowed combination is an index you either build or a sort the database performs on every request. PostgreSQL sorts NULL as larger than any value, so NULLs come last ascending and first descending; writing NULLS LAST for nullable columns keeps undated issues at the end in both directions. An index serves the query without a separate sort only when its columns, directions and NULL placement match the ORDER BY or its exact reverse. Always append the unique id, so the order is total and a page boundary is a single row, which the pagination lesson relies on for cursors. Choose a default order when the client sends none rather than leaving it to the planner.

06

Test the builder as a pure function

Because buildQuery takes url.Values and returns a string and a slice, its tests need no database and no HTTP server. For each case, assert the full SQL text and the full argument list, not a substring. Include equivalence cases that must produce identical output, such as reordered and repeated list values, and hostile cases that must produce 400: an unencoded semicolon, an unknown parameter, an unknown or repeated sort key, an out-of-range limit, twenty-one assignees and an over-long search term. Then add a small integration suite against a disposable PostgreSQL that checks rows rather than strings: a title containing a literal percent sign, NULL placement in both directions, and EXPLAIN for each allowed sort combination to confirm the index you expect is used.

TAKE THIS WITH YOU

Parse RawQuery strictly, canonicalize and bound every list, let a builder generate every placeholder, take sort SQL only from constants and always end the order with a unique tiebreaker.

Check your understanding

A Gin handler reads filters with c.QueryArray("status"). In Go 1.17 and later, what happens to the request ?status=open;closed?

Go to the source

Progress stays in this browser. No account needed.