Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Binding and Validation

Binding Query, URI and Headers in Gin

Bind query strings, path parameters and HTTP headers into Go structs with ShouldBindQuery, ShouldBindUri and ShouldBindHeader, set defaults, and build a runnable reflection-based binder stand-in.

A request carries data in more places than the body. The query string holds filters and paging (?page=2&sort=title), the path holds identifiers (/books/42), and headers hold things like Authorization or Accept-Language. In Path and Query Parameters you read them one at a time with c.Query and c.Param. Binding reads them all at once into a struct and, combined with validation, gives you typed, checked input in a single line.

This lesson follows Binding JSON and Forms; the rules from validation rules work identically on every binder.

Gin is not available on this site, so Gin code is read-only. The runnable stand-ins are plain Go, including a small reflection-based binder that works like Gin's form binder so you can see what happens inside.

Query binding: ShouldBindQuery

Use the form tag (yes, form, not query) on fields, and call ShouldBindQuery:

Go
type ListBooks struct {
	Page     int      `form:"page,default=1"`
	PageSize int      `form:"page_size,default=20"`
	Sort     string   `form:"sort"`
	Tags     []string `form:"tag"`
	InStock  bool     `form:"in_stock"`
}

r.GET("/books", func(c *gin.Context) {
	var q ListBooks
	if err := c.ShouldBindQuery(&q); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, q)
})

A request to /books?page=3&tag=go&tag=web&in_stock=true fills Page=3, PageSize=20 (the default), Tags=[go web] and InStock=true. Three details matter:

  • default=1 inside the tag supplies a value when the key is missing. Test how your Gin version treats a present-but-empty value (?page=) before relying on it; the stand-in below applies defaults only when the key is absent.
  • Repeated keys fill slices. Comma-separated lists (?tag=go,web) are not split unless you add collection_format:"csv" to the tag.
  • A value that cannot be converted (?page=abc) returns an error, which you should turn into a 400.

ShouldBindQuery only looks at the URL. A plain ShouldBind on a GET request also reads the query, but on a POST it reads the body, which is a common source of confusion. Be explicit.

URI binding: ShouldBindUri

Path parameters use the uri tag:

Go
type BookURI struct {
	ID int `uri:"id" binding:"required,min=1"`
}

r.GET("/books/:id", func(c *gin.Context) {
	var u BookURI
	if err := c.ShouldBindUri(&u); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"id": u.ID})
})

The benefit over strconv.Atoi(c.Param("id")) is that the conversion and the range check happen in one place, and an invalid path such as /books/abc is rejected before your logic runs. With groups you can validate the same struct for a whole set of routes, for example by binding in a middleware that sits on /books/:id.

Header binding: ShouldBindHeader

Headers use the header tag. Names are matched case-insensitively, as HTTP requires:

Go
type Meta struct {
	Language  string `header:"Accept-Language"`
	RequestID string `header:"X-Request-Id" binding:"required"`
	Token     string `header:"Authorization"`
}

r.GET("/whoami", func(c *gin.Context) {
	var m Meta
	if err := c.ShouldBindHeader(&m); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, m)
})

For authentication you will usually read Authorization in middleware instead (see Writing Custom Middleware), but header binding is handy for request ids, API versions and client hints.

Combining several sources

One request often needs several binders. Call them in turn on separate structs and keep each struct small:

Go
r.GET("/shops/:shop_id/books", func(c *gin.Context) {
	var uri struct {
		ShopID int `uri:"shop_id" binding:"required"`
	}
	var q ListBooks
	if err := c.ShouldBindUri(&uri); err != nil { /* 400 */ return }
	if err := c.ShouldBindQuery(&q); err != nil { /* 400 */ return }
	// use uri.ShopID and q together
})

Binding one struct from two sources is possible (it needs both uri and form tags and two calls on the same variable), but separate structs make it obvious which part of the request is which, and prevent a client from overriding an identifier through the query string.

Stand-in: a tiny query binder

Gin's form binder reads struct tags with reflection, converts strings to field types and applies defaults. This stand-in implements the same four ideas for strings, ints, bools and string slices, so you can see it work.

Go Stand-in: reflection-based query binder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Read the output: the empty query still produces Page:1 Size:20 thanks to the defaults, repeated tag keys become a slice, and page=abc produces an error. Gin's real binder handles many more types (floats, unsigned numbers, time, maps, nested structs) and reports richer errors, but the mechanism is the same.

Stand-in: path values and headers

Since Go 1.22 the standard mux gives you path parameters through r.PathValue, and headers are a plain map. This runnable example binds both into one struct, mimicking ShouldBindUri plus ShouldBindHeader with validation:

Go Stand-in: URI plus header binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Binding order and gotchas

  • Binding happens when you call the method, not automatically. No call, no data.
  • Query keys and header names are case-sensitive for query (Page is not page) but case-insensitive for headers.
  • A struct bound from the URL should hold strings, numbers, bools, slices and time.Time. Nested objects need the form:"user.name" style or JSON instead.
  • Put defaults on the server side. Never rely on the client to send page.
  • Cap what clients may ask for: binding:"max=100" on a page size stops ?size=1000000.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which struct tag does ShouldBindQuery use?

    Gin reuses the form tag for query strings, so the same struct can serve a form POST and a GET query.
  2. 2. How do you give a missing query parameter a default value in the tag?

    The default= option follows the key name inside the form tag.
  3. 3. Which method reads values from the path /books/:id?

    ShouldBindUri uses the uri tag and the route's named parameters.
  4. 4. Why bind the URI and the query into separate structs?

    Separate structs make the origin of each value obvious and avoid accidental overrides.

Summary

  • ShouldBindQuery (tag form), ShouldBindUri (tag uri) and ShouldBindHeader (tag header) fill structs from the URL, the path and the headers.
  • Use default= for optional query values and collection_format:"csv" for comma lists.
  • Keep one small struct per source and combine them in the handler.
  • Conversion errors are client errors: answer with 400.
  • Validation tags (binding:"required,min=1") apply to every binder.

Next: Validation Rules covers the binding tag and the full set of built-in validators.