Gin foundations · 5 MIN READ
Query strings and forms in Gin: tell absent from empty, parse numbers strictly, bound every limit
Read query and form values with the Gin helper that matches the case, convert them with strconv and reject bad input with a clear 400.
Every query or form value reaches your handler as a string that may be missing, empty, repeated or malformed. Gin offers several helpers that look interchangeable but answer different questions. Choosing the wrong one turns limit=abc into limit 0, or a deliberately empty field into a default the client never asked for.
gin · A MAP OF THE IDEA
- Name absent vs empty
- Pick the matching helper
- Parse with strconv
- Bound and report 400
Useful when
- GetQuery and GetPostForm make absent and empty explicit.
- One contract-style message per parameter stays stable across refactors.
Watch out
- A '+' in a query string is a space, so +7 does not parse as an integer.
- Form parse errors are swallowed by the helpers unless you call ParseForm yourself.
Implementation & operation cost: A small helper per parameter type and a table test; the alternative is declarative binding, covered later, which trades visibility for brevity.
Four states hide behind one string
For any key a request can be in one of four states: absent, present but empty, present and valid, or present and invalid. c.Query collapses the first two into "". c.GetQuery returns the value plus a boolean that is true even for ?q= and for a bare ?q. c.DefaultQuery substitutes its default only when the key is absent. The form helpers PostForm, GetPostForm and DefaultPostForm follow the same rules for the request body. Decide for each parameter what absent and empty mean, then pick the helper that can express that decision.
A search endpoint and a form endpoint
The program implements GET /search with a required q, a bounded limit, repeatable tag values and a filter map, plus POST /notes reading a URL-encoded form. Nine requests cover the default path, three kinds of bad limit, a present-but-empty q, the full happy path, an unknown filter key and the two form cases.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// intQuery returns def when key is absent and rejects present values
// that are not integers inside [lo, hi].
func intQuery(c *gin.Context, key string, def, lo, hi int) (int, error) {
raw, ok := c.GetQuery(key)
if !ok {
return def, nil
}
n, err := strconv.Atoi(raw)
if err != nil || n < lo || n > hi {
return 0, fmt.Errorf("%s must be an integer between %d and %d", key, lo, hi)
}
return n, nil
}
var filterKeys = map[string]bool{"status": true, "owner": true}
func search(c *gin.Context) {
q, ok := c.GetQuery("q")
if !ok || strings.TrimSpace(q) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "q is required"})
return
}
limit, err := intQuery(c, "limit", 20, 1, 100)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
tags := c.QueryArray("tag")
if len(tags) > 5 {
c.JSON(http.StatusBadRequest, gin.H{"error": "at most 5 tag values"})
return
}
filter := c.QueryMap("filter")
for k := range filter {
if !filterKeys[k] {
c.JSON(http.StatusBadRequest, gin.H{"error": "unknown filter " + k})
return
}
}
c.JSON(http.StatusOK, gin.H{"q": q, "limit": limit, "tags": tags, "filter": filter})
}
func createNote(c *gin.Context) {
title, ok := c.GetPostForm("title")
if !ok || title == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})
return
}
priority := c.DefaultPostForm("priority", "normal")
switch priority {
case "low", "normal", "high":
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "priority must be low, normal or high"})
return
}
c.JSON(http.StatusCreated, gin.H{"title": title, "priority": priority})
}
func main() {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/search", search)
r.POST("/notes", createNote)
for _, target := range []string{
"/search?q=gin",
"/search?q=gin&limit=abc",
"/search?q=gin&limit=500",
"/search?q=gin&limit=+7",
"/search?q=&tag=go",
"/search?q=gin&limit=5&tag=go&tag=web&filter[status]=open",
"/search?q=gin&filter[secret]=1",
} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))
fmt.Println(w.Code, w.Body.String())
}
for _, form := range []string{"title=Ship+it", "title=Ship+it&priority="} {
req := httptest.NewRequest(http.MethodPost, "/notes", strings.NewReader(form))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
fmt.Println(w.Code, w.Body.String())
}
}intQuery returns the default only when the key is absent; a present value must parse and fall in range, otherwise the client gets one message that states the contract. limit=+7 fails because '+' in a query string decodes to a space, so strconv.Atoi sees " 7". q= is present, so GetQuery reports ok and the TrimSpace check rejects it. QueryArray collects repeated tag values in order and returns nil when there are none, which JSON renders as null. QueryMap turns filter[status]=open into a map, and the loop rejects keys outside the allowlist. The last request sends priority= explicitly, so DefaultPostForm returns "" instead of "normal" and the switch rejects it.
Repeated, bracketed and malformed keys
When a key repeats, GetQuery and Query return the first value and QueryArray returns all of them. QueryMap and PostFormMap read bracket keys such as filter[status]; the result is a Go map, so never let its iteration order reach output or logic that must be stable (encoding/json sorts map keys, which is why the program's output is deterministic). A malformed escape such as %zz is dropped by Go's query parser and Gin does not surface the error, so the key simply looks absent. Forms have a second trap: PostForm reads only the parsed body, never the query string, and Gin's form cache logs a parse failure only in debug mode. A truncated or oversized body therefore shows up as missing fields. When that difference matters, parse explicitly first.
func createNote(c *gin.Context) {
// Parse explicitly so a malformed or truncated body becomes a 400
// instead of a field that silently looks absent.
if err := c.Request.ParseForm(); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "malformed form body"})
return
}
title, ok := c.GetPostForm("title") // reads the parsed body only
// ...
}This fragment shows the explicit parse step. Request.ParseForm reads URL-encoded bodies and the query string and returns the first error it meets, including an invalid escape or a body cut off by http.MaxBytesReader. After it succeeds Gin's helpers reuse the parsed values, because ParseForm does not parse twice. GetPostForm still looks only at Request.PostForm, the body values.
strconv is strict; your error message should be too
strconv.Atoi accepts an optional sign and leading zeros, so "+7", "007" and "-1" parse, while " 5", "1e3" and "0x10" are syntax errors and "99999999999999999999" fails with strconv.ErrRange. Use strconv.ParseInt(raw, 10, 32) when the value must fit an int32 column. Do not echo the Go error text to clients: it describes your implementation, not your contract. A message such as "limit must be an integer between 1 and 100" tells a caller exactly how to fix the request and stays stable when you refactor. Use 400 Bad Request for malformed query parameters and keep the error body shape the same across endpoints.
Bound every parameter that sizes the work
A limit decides how many rows the database reads, how much JSON the server encodes and how long the response holds a connection, so it needs a ceiling as well as a default. An offset needs one too: OFFSET 100000 still makes most databases walk 100000 rows, which is why deep pagination usually moves to a cursor. Cap repeated values, because each tag tends to become another predicate, and allowlist map keys, because filter keys are often mapped to column names and must never be interpolated into SQL. Rejecting out-of-range values surfaces client bugs early; clamping is friendlier for interactive UIs, but if you clamp, echo the effective limit as the program does so the client can see it. Test each parameter as a table: absent, empty, non-numeric, below and above the bounds, '+' and '%2B', repeated, malformed escape and unknown map key. The binding-sources lesson later in this course shows how ShouldBindQuery with form tags and default= values expresses the same rules declaratively.
TAKE THIS WITH YOU
Use GetQuery or GetPostForm when absent and empty mean different things, parse numbers with strconv and a stated range, and give every limit-style parameter a default, a ceiling and a clear 400 message.
Check your understanding
When does c.DefaultQuery("limit", "20") return "20" instead of a value from the request?
Go to the source
Progress stays in this browser. No account needed.