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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Named parameters use a leading colon in the route and are read by name with c.Param.
- 2A wildcard parameter prefixed with * captures the remaining path segment, including a leading slash.
- 3Route registration and handler logic stay cleanly separated, making the URL contract easy to scan.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/reading-path-parameters-in-gin-explained-go-ef7b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.