Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Routing and Handlers

Path and Query Parameters in Gin

Read values from the URL in Gin with c.Param, wildcards, c.Query, DefaultQuery, query arrays and maps, and form fields; convert and validate them safely with runnable examples.

Most requests carry data in the URL. A path like /users/42 identifies which resource, and a query string like ?page=2&sort=name refines how you want it. Gin gives you short methods for both, plus form fields in a request body. This lesson shows each one, how to convert the strings you get into numbers safely, and the traps to avoid. It follows Routes and HTTP Methods.

Path parameters

A segment that starts with a colon is a named parameter. It matches exactly one path segment (never a slash):

Go
r.GET("/users/:id", func(c *gin.Context) {
	id := c.Param("id")
	c.JSON(http.StatusOK, gin.H{"id": id})
})

GET /users/42 gives id == "42". /users/42/extra does not match, and neither does /users/ (the parameter cannot be empty). You can use several parameters in one path:

Go
r.GET("/orgs/:org/repos/:repo", func(c *gin.Context) {
	c.String(http.StatusOK, "%s/%s", c.Param("org"), c.Param("repo"))
})

Remember: c.Param always returns a string. A parameter named id is not a number until you convert it.

Wildcards (catch-all)

A segment that starts with an asterisk matches the whole rest of the path, including slashes, and must be last:

Go
r.GET("/files/*filepath", func(c *gin.Context) {
	c.String(http.StatusOK, "file: %s", c.Param("filepath"))
})

For GET /files/docs/guide.pdf the value of filepath is /docs/guide.pdf, with a leading slash. The wildcard also matches /files/ itself (value /). Static file serving uses this kind of route internally.

Route conflicts

Gin's router is a radix tree, which is why it is fast, and it has one rule worth knowing: at the same position, two routes with different parameter names conflict, and Gin panics at startup:

Go
r.GET("/users/:id", a)
r.GET("/users/:name", b) // panic: wildcard route conflicts with existing

Use the same name everywhere. Recent Gin versions do allow a fixed segment next to a parameter, such as /users/me beside /users/:id, and the fixed one wins. Because registration errors appear as panics at startup, you find them as soon as you run the program.

Reading and converting values

Since every value is a string, convert it and handle failure. The stand-in below uses the Go 1.22 PathValue method, which plays the role of c.Param:

Go Stand-in: path parameters with validation

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.

In Gin you can skip the manual conversion for IDs by using a URI binding struct, covered in Binding Query, URI and Headers.

Query parameters

The query string is everything after ?. Gin offers:

Go
r.GET("/search", func(c *gin.Context) {
	q := c.Query("q")                       // "" if missing
	page := c.DefaultQuery("page", "1")     // "1" if missing
	sort, ok := c.GetQuery("sort")          // ok is false if missing
	tags := c.QueryArray("tag")             // ?tag=go&tag=web -> ["go","web"]
	filters := c.QueryMap("filter")         // ?filter[color]=red -> {"color":"red"}

	c.JSON(http.StatusOK, gin.H{
		"q": q, "page": page, "sort": sort, "sortGiven": ok,
		"tags": tags, "filters": filters,
	})
})

c.Query cannot tell a missing parameter from an empty one (?q=). When that difference matters, use GetQuery, which returns a second boolean. A request such as GET /search?q=gin&tag=go&tag=web&filter[color]=red produces the values in the comments above.

The standard library has the same machinery in net/url, which is what Gin uses underneath:

Go Query strings with net/url (what Gin does inside)

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.

Queries are the right place for optional things: filtering, sorting, paging, searching. Use the path for the identity of a resource.

A paging helper

Most list endpoints need page and limit. Parse them defensively and cap limit, otherwise a client can ask for limit=1000000:

Go
func paging(c *gin.Context) (page, limit int) {
	page, _ = strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ = strconv.Atoi(c.DefaultQuery("limit", "20"))
	if page < 1 {
		page = 1
	}
	if limit < 1 || limit > 100 {
		limit = 20
	}
	return page, limit
}

Form fields in the body

When a browser submits an HTML form with POST, the fields come in the body (application/x-www-form-urlencoded or multipart/form-data). The matching methods start with Post:

Go
r.POST("/login", func(c *gin.Context) {
	user := c.PostForm("username")
	remember := c.DefaultPostForm("remember", "off")
	roles := c.PostFormArray("role")
	c.JSON(http.StatusOK, gin.H{"user": user, "remember": remember, "roles": roles})
})

c.Query reads only the URL; c.PostForm reads only the body. If a value may arrive either way, c.GetPostForm and c.GetQuery are separate calls. Never put passwords or tokens in a query string: URLs end up in browser history, server logs and Referer headers.

Go Stand-in: PostForm and Query side by side

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.

Reading other parts of the request

The context also exposes the raw request when you need more: c.GetHeader("User-Agent"), c.ClientIP(), c.Request.Method, c.Request.URL.Path, c.FullPath() (the route pattern such as /users/:id, useful for metrics because it has low cardinality), and c.Cookie("session").

Common mistakes

  • Trusting parameters as numbers. c.Param("id") is text; always convert and check the error.
  • Unbounded limit values. Cap them.
  • Mixing parameter names at the same tree position (:id and :name), which panics at startup.
  • Expecting /files/*path to give a value without a leading slash. It starts with /.
  • Using the query for secrets. Use headers or the body.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type does c.Param("id") return?

    Parameters are always strings. Convert with strconv.Atoi or use URI binding.
  2. 2. For the route /files/*filepath and the request /files/a/b.txt, what is c.Param("filepath")?

    A catch-all parameter includes the leading slash.
  3. 3. Which call tells you whether a query parameter was present at all?

    GetQuery returns the value and a boolean that is false when the parameter is missing, so you can tell missing from empty.
  4. 4. What does c.QueryArray("tag") return for ?tag=go&tag=web?

    QueryArray collects every value of a repeated parameter into a []string.
  5. 5. Why is it wrong to send a password in a query string?

    URLs leak into many places. Send secrets in the body or in a header over HTTPS.

Summary

  • :name matches one path segment; *name matches the rest of the path, with a leading slash.
  • c.Param returns strings; convert and validate them.
  • c.Query, c.DefaultQuery, c.GetQuery, c.QueryArray and c.QueryMap read the query string.
  • c.PostForm and friends read form fields from the body.
  • Use the same parameter name at the same position, cap paging limits, and keep secrets out of URLs.

Next: Route Groups organizes related routes under a shared prefix.