Gin foundations · 5 MIN READ

Gin binding sources: bind path, query, headers and body separately, and cache the body to read it twice

Bind each request source with its own Gin binder and tag, predict what content-type-driven ShouldBind reads, and decode one body twice with ShouldBindBodyWithJSON.

A single request carries input in four places: path parameters, the query string, headers and the body. Gin has a binder and a struct tag for each, and they compose well as long as you respect two rules the API does not advertise. Every binder validates the entire struct it fills, and a request body can be read only once unless you ask Gin to keep a copy.

gin · A MAP OF THE IDEA

  1. One struct per source
  2. Bind path, query, headers
  3. Bind the body last
  4. Cache body to read twice

Useful when

  • Each error names the source that was wrong.
  • default= options keep simple query defaults declarative.

Watch out

  • ShouldBind falls back to form binding for unknown content types.
  • ShouldBindBodyWith buffers the whole body; cap its size first.

Implementation & operation cost: A few small structs per endpoint and one extra in-memory copy of the body when it must be decoded twice.

01

Four sources, four tags, one binder each

ShouldBindUri fills fields tagged uri from c.Params. ShouldBindQuery fills form-tagged fields from the URL query only. ShouldBindHeader fills header-tagged fields, canonicalizing the tag with textproto.CanonicalMIMEHeaderKey, so header:"x-request-id" works. ShouldBindJSON decodes the body into json-tagged fields. After mapping, every binder runs the validator, which reads the binding tag. The Should variants return the error and leave the response to you; the Bind variants abort with a bare 400 and, in v1.12.0, no body at all, which is rarely the error contract an API wants. A form tag can carry a default, as in form:"limit,default=20", which applies only when the key is absent.

02

Path, query, headers, body and a webhook

The program defines one small struct per source and wires them into five handlers: a list endpoint with path, query and header input, a PATCH that needs an If-Match header, a create endpoint that accepts JSON or a form through ShouldBind, and two webhook handlers that read the same body twice, one correctly and one naively.

go
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

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

// One small struct per source: each binder validates the whole struct it fills.
type projectURI struct {
	Project string `uri:"project" binding:"required,alphanum,max=32"`
}

type listQuery struct {
	Limit int    `form:"limit,default=20" binding:"min=1,max=100"`
	Sort  string `form:"sort,default=created" binding:"oneof=created title"`
}

type traceHeader struct {
	RequestID string `header:"X-Request-Id"`
}

type noteURI struct {
	ID int64 `uri:"id" binding:"required,min=1"`
}

type patchHeader struct {
	IfMatch string `header:"If-Match" binding:"required"`
}

type patchBody struct {
	Title string `json:"title" binding:"required,max=80"`
}

type createNote struct {
	Title string `json:"title" form:"title" binding:"required,max=80"`
}

type envelope struct {
	Type string `json:"type" binding:"required"`
}

type noteCreated struct {
	Data struct {
		ID    int64  `json:"id" binding:"required"`
		Title string `json:"title" binding:"required"`
	} `json:"data"`
}

func bad(c *gin.Context, source string) {
	c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid " + source})
}

func listNotes(c *gin.Context) {
	var uri projectURI
	var q listQuery
	var h traceHeader
	if c.ShouldBindUri(&uri) != nil {
		bad(c, "path")
		return
	}
	if c.ShouldBindQuery(&q) != nil {
		bad(c, "query")
		return
	}
	if c.ShouldBindHeader(&h) != nil {
		bad(c, "headers")
		return
	}
	c.JSON(http.StatusOK, gin.H{"project": uri.Project, "limit": q.Limit, "sort": q.Sort, "request_id": h.RequestID})
}

func patchNote(c *gin.Context) {
	var uri noteURI
	var h patchHeader
	var body patchBody
	if c.ShouldBindUri(&uri) != nil {
		bad(c, "path")
		return
	}
	if c.ShouldBindHeader(&h) != nil {
		bad(c, "headers")
		return
	}
	if c.ShouldBindJSON(&body) != nil {
		bad(c, "body")
		return
	}
	c.JSON(http.StatusOK, gin.H{"id": uri.ID, "if_match": h.IfMatch, "title": body.Title})
}

func postNote(c *gin.Context) {
	var in createNote
	if err := c.ShouldBind(&in); err != nil {
		bad(c, "body")
		return
	}
	c.JSON(http.StatusCreated, gin.H{"title": in.Title, "via": c.ContentType()})
}

func webhook(c *gin.Context) {
	var env envelope
	if c.ShouldBindBodyWithJSON(&env) != nil {
		bad(c, "envelope")
		return
	}
	switch env.Type {
	case "note.created":
		var ev noteCreated
		if c.ShouldBindBodyWithJSON(&ev) != nil {
			bad(c, "note.created payload")
			return
		}
		c.JSON(http.StatusAccepted, gin.H{"handled": env.Type, "id": ev.Data.ID})
	default:
		c.JSON(http.StatusAccepted, gin.H{"ignored": env.Type})
	}
}

func webhookNaive(c *gin.Context) {
	var env envelope
	var ev noteCreated
	_ = c.ShouldBindJSON(&env)
	if err := c.ShouldBindJSON(&ev); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"second_read": err.Error()})
		return
	}
	c.Status(http.StatusAccepted)
}

func main() {
	gin.SetMode(gin.TestMode)
	r := gin.New()
	r.GET("/projects/:project/notes", listNotes)
	r.PATCH("/notes/:id", patchNote)
	r.POST("/notes", postNote)
	r.POST("/webhooks", webhook)
	r.POST("/webhooks-naive", webhookNaive)

	const event = `{"type":"note.created","data":{"id":9,"title":"Hi"}}`
	cases := []struct {
		method, target, contentType, body string
		headers                           map[string]string
	}{
		{"GET", "/projects/core/notes", "", "", nil},
		{"GET", "/projects/core/notes?limit=0", "", "", nil},
		{"GET", "/projects/core/notes?limit=5&sort=title", "", "", map[string]string{"X-Request-Id": "r-42"}},
		{"GET", "/projects/core.v2/notes", "", "", nil},
		{"PATCH", "/notes/abc", "application/json", `{"title":"Renamed"}`, nil},
		{"PATCH", "/notes/7", "application/json", `{"title":"Renamed"}`, nil},
		{"PATCH", "/notes/7", "application/json", `{"title":"Renamed"}`, map[string]string{"If-Match": `"v3"`}},
		{"POST", "/notes", "application/json", `{"title":"From JSON"}`, nil},
		{"POST", "/notes", "application/x-www-form-urlencoded", "title=From+a+form", nil},
		{"POST", "/webhooks", "application/json", event, nil},
		{"POST", "/webhooks-naive", "application/json", event, nil},
	}
	for _, tc := range cases {
		req := httptest.NewRequest(tc.method, tc.target, strings.NewReader(tc.body))
		if tc.contentType != "" {
			req.Header.Set("Content-Type", tc.contentType)
		}
		for k, v := range tc.headers {
			req.Header.Set(k, v)
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Println(tc.method, tc.target, w.Code, w.Body.String())
	}
}
Read the code

The first request gets limit 20 and sort created from the default= options. limit=0 is present, so the default does not apply and min=1 rejects it. core.v2 fails alphanum in the path. /notes/abc fails before validation because strconv cannot parse an int64. The PATCH without If-Match fails header validation, and the one with it echoes the quoted entity tag. ShouldBind picks the JSON or form binder from Content-Type, so both create requests succeed. /webhooks decodes the envelope, switches on its type, then decodes the full payload from the cached bytes. /webhooks-naive calls ShouldBindJSON twice; the first call drained the body, so the second sees EOF.

03

Why one struct per source

It is tempting to describe a whole request in one struct with uri, json and header tags side by side. Each binder maps only its own tag, but binding.Uri, binding.Query, binding.Header and the body binders all validate the complete struct afterwards. A required body field is therefore still empty when ShouldBindUri runs, and the call fails on a perfectly valid request. Separate structs per source avoid the problem and also make the error message honest: you know which source was wrong. If you insist on one struct, the only arrangement that works is to put binding rules solely on the fields filled by the binder you call last, which quietly gives up validation for every other source.

go
// Looks tidy, fails on every request.
type patchNoteRequest struct {
	ID    int64  `uri:"id" binding:"required,min=1"`
	Title string `json:"title" binding:"required,max=80"`
}

var in patchNoteRequest
err := c.ShouldBindUri(&in)
// Key: 'patchNoteRequest.Title' Error:Field validation for 'Title'
// failed on the 'required' tag
Read the code

This fragment is the anti-pattern, with the v1.12.0 error text as a comment. ShouldBindUri sets ID correctly, then validation reaches Title, which is empty because the JSON body has not been decoded yet, and required fails. Swapping the call order only moves the failure: ShouldBindJSON would then complain about ID.

04

Content-Type decides what ShouldBind reads

ShouldBind asks binding.Default(method, contentType) for a binder. For GET it always returns the form binder, so a JSON body on a GET is ignored and only the query string is read. For other methods the media type, with parameters such as charset stripped, selects JSON, XML, YAML, TOML, protobuf, MessagePack, BSON or multipart. Anything else, including a missing Content-Type or text/plain, falls back to the form binder, which reads Request.Form: the URL-encoded body merged with the query string, body values first. A client can therefore supply a field through the query string of a POST. If an endpoint accepts only JSON, call ShouldBindJSON and answer 415 for other content types instead of letting the fallback guess.

05

Reading the body twice without losing it

Request.Body is a stream; once a decoder has consumed it, the next read returns EOF. ShouldBindBodyWith(obj, binding.JSON), or the shortcut ShouldBindBodyWithJSON, reads the whole body with io.ReadAll on first use, stores the bytes in c.Keys under gin.BodyBytesKey and decodes from that copy on every later call. That is what an envelope-then-payload webhook needs. It only works with body binders such as JSON, XML, YAML, TOML and Plain, not with the form binder, and once one call has cached the body every other read in that request must use the BodyWith variants too. Because the whole body is buffered in memory, put http.MaxBytesReader in front of it as described in the binding-limits lesson; that lesson also covers when to reject unknown fields.

06

Test each source on its own

Write table cases per source rather than per endpoint: a path value of the wrong type, a query key that is absent versus present with a zero value, a header in unusual case, a body with no Content-Type, an empty body, and a second read of the same body. Assert both the status and which source the error names, because a test that only checks for 400 cannot tell a header mistake from a body mistake. The next lesson turns validator errors into a stable field-level JSON response.

TAKE THIS WITH YOU

Give each request source its own struct and binder, call ShouldBindJSON when only JSON is acceptable, and use ShouldBindBodyWithJSON behind a size limit when one body must be decoded twice.

Check your understanding

A struct has a uri-tagged ID and a json-tagged Title, both binding:"required". Why does ShouldBindUri fail on a valid request?

Go to the source

Progress stays in this browser. No account needed.