go 37 lines · 7 steps

Reading path parameters in Gin

How Gin declares named and wildcard path parameters in route patterns and reads them back inside handlers.

Explained by highlit
1package handlers
2 
3import (
4 "net/http"
5 
6 "github.com/gin-gonic/gin"
7)
8 
9// RegisterUserRoutes wires up routes that demonstrate extracting path
10// parameters via c.Param. Parameters are declared with a leading colon
11// in the route pattern and read back by name inside the handler.
12func RegisterUserRoutes(r *gin.Engine) {
13 r.GET("/users/:id", getUser)
14 r.GET("/users/:id/posts/:postID", getUserPost)
15 // A wildcard parameter (prefixed with *) captures the rest of the path.
16 r.GET("/files/*filepath", serveFile)
17}
18 
19func getUser(c *gin.Context) {
20 id := c.Param("id")
21 c.JSON(http.StatusOK, gin.H{"userID": id})
22}
23 
24func getUserPost(c *gin.Context) {
25 userID := c.Param("id")
26 postID := c.Param("postID")
27 c.JSON(http.StatusOK, gin.H{
28 "userID": userID,
29 "postID": postID,
30 })
31}
32 
33func serveFile(c *gin.Context) {
34 // Wildcard values always include a leading slash, e.g. "/docs/readme.md".
35 path := c.Param("filepath")
36 c.JSON(http.StatusOK, gin.H{"path": path})
37}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Named parameters use a leading colon in the route and are read by name with c.Param.
  2. 2A wildcard parameter prefixed with * captures the remaining path segment, including a leading slash.
  3. 3Route registration and handler logic stay cleanly separated, making the URL contract easy to scan.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Reading path parameters in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code