Gin foundations · 6 MIN READ
Path parameters in Gin: :param takes one segment, *wildcard takes the rest, conflicts panic at boot
Declare Gin route templates with :param and *wildcard, predict how slashes and escapes resolve, and label metrics with c.FullPath().
Every Gin route is a template stored in a radix tree. The router decides which handler runs, what c.Param returns and whether the client gets a redirect instead of your handler. Most routing bugs are not in handler code: they are a trailing slash, an encoded slash or two templates that cannot share a prefix. Learn the matching rules once and those bugs become predictable.
gin · A MAP OF THE IDEA
- Declare route templates
- Resolve conflicts at boot
- Choose slash policy
- Label by FullPath
Useful when
- Conflicting templates fail at registration, before any traffic.
- FullPath gives a stable, bounded route label for logs and metrics.
Watch out
- Trailing-slash redirects are written before middleware, so access logs miss them.
- Enabling UseRawPath lets parameters contain '/', which handlers must validate.
Implementation & operation cost: No runtime cost beyond the radix-tree lookup; the work is deciding a slash and encoding policy and pinning it with a table test.
A route is a template matched segment by segment
A named parameter such as :id matches exactly one non-empty path segment: it stops at the next slash and never matches an empty string. A catch-all such as *path must be the last element of the template and captures everything after its position, including the leading slash. There are no regular expressions and no types in the template, so /users/:id accepts "42", "abc" and "-1" alike; turning the string into a number or a UUID is the handler's job. A static segment registered next to a parameter wins when it matches exactly, which is why /users/new and /users/:id can coexist in Gin v1.12.0.
Watch the router resolve real paths
The program registers four templates on one engine and sends nine requests. Each handler prints the matched template and every parameter in path order, so you can see what the router decided rather than what you expected. The last request goes to a second engine with UseRawPath enabled to show why one encoded character changes the outcome.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/gin-gonic/gin"
)
func describe(c *gin.Context) {
var b strings.Builder
b.WriteString(c.FullPath())
for _, p := range c.Params {
fmt.Fprintf(&b, " %s=%q", p.Key, p.Value)
}
c.String(http.StatusOK, b.String())
}
func newRouter() *gin.Engine {
r := gin.New()
r.GET("/users/:id", describe)
r.GET("/users/new", describe)
r.GET("/users/:id/posts/:slug", describe)
r.GET("/files/*path", describe)
return r
}
func send(r *gin.Engine, path string) {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
detail := w.Body.String()
if loc := w.Header().Get("Location"); loc != "" {
detail = "Location: " + loc
}
fmt.Println(path, w.Code, detail)
}
func main() {
gin.SetMode(gin.TestMode)
r := newRouter()
for _, path := range []string{
"/users/42",
"/users/new",
"/users/42/posts/hello-gin",
"/files/docs/guide.pdf",
"/files/",
"/users/42/",
"/users/",
"/users/a%2Fb",
} {
send(r, path)
}
raw := newRouter()
raw.UseRawPath = true
send(raw, "/users/a%2Fb")
}describe prints c.FullPath() and ranges over c.Params, which preserves path order. /users/new hits the static route, not :id. The catch-all keeps the leading slash, so /files/ yields path="/". /users/42/ never reaches a handler: RedirectTrailingSlash answers 301 with Location /users/42. /users/ is a 404 because :id cannot be empty. /users/a%2Fb is a 404 on the default engine because Gin routes on the decoded URL.Path, where %2F has become a real slash and splits the segment. With UseRawPath the router matches the encoded form and UnescapePathValues hands the handler id="a/b".
Conflicts fail at startup, which is the good news
Two templates cannot put different wildcards at the same position, and a catch-all cannot share its level with anything else. Gin enforces this when the route is added, by panicking, so a conflicting route table never serves a single request. Treat that panic as a design signal: either the URLs describe different resources and need different prefixes, or one handler should own the position and branch on the value. Registering the same method and path twice also panics with "handlers are already registered".
// Each pair below panics when both routes are registered on one engine.
r.GET("/users/:id", show)
r.GET("/users/:name/posts", show)
// ':name' in new path '/users/:name/posts' conflicts with existing wildcard ':id' ...
r.GET("/files/:id", show)
r.GET("/files/*path", show)
// '*path' in new path '/files/*path' conflicts with existing wildcard ':id' ...
r.GET("/assets/*path", show)
r.GET("/assets/readme", show)
// '/readme' in new path '/assets/readme' conflicts with existing wildcard '/*path' ...
r.GET("/raw/*path/meta", show)
// catch-all routes are only allowed at the end of the path ...This fragment is not compiled; show stands for any handler. The messages are the start of the v1.12.0 panic text. The first pair fails because :id and :name compete for the same segment, even though the second template is longer. The second and third pairs fail because *path claims the whole remainder of /files/ or /assets/, leaving no room for :id or readme. The last line fails on its own: nothing may follow a catch-all. Because these are panics at registration, a test that only calls newRouter() catches them.
Trailing slashes, case and doubled slashes
Three engine flags decide what happens to paths that almost match. RedirectTrailingSlash is on by default: GET requests get a 301, other methods a 307 so the body and method survive, and the query string is kept. The redirect is written before the handler chain runs, so your logging and metrics middleware never see it; if a client keeps hitting /users/42/, only the proxy log will show the extra round trips. It also honors an X-Forwarded-Prefix request header, sanitized to letters, digits, '/' and '-'. RedirectFixedPath is off by default; when enabled it cleans ../ and // and does a case-insensitive lookup, so /USERS/AbC redirects to /users/AbC with the parameter's case preserved. RemoveExtraSlash cleans the path before lookup and serves it directly, without a redirect. For browser-facing pages the redirects are friendly. For a machine API, a 404 on the non-canonical path can be the better contract: it fails loudly in the client's tests instead of costing a hidden round trip on every call.
r := gin.New()
// Defaults in v1.12.0, written out so a reviewer sees the policy.
r.RedirectTrailingSlash = true // /users/42/ -> 301 (GET) or 307 (other methods)
r.RedirectFixedPath = false // true: /USERS//42 -> 301 /users/42
r.RemoveExtraSlash = false // true: //users//42 is served as /users/42, no redirect
r.UseRawPath = false // true: match on URL.RawPath when Go recorded one
r.UseEscapedPath = false // true: match on URL.EscapedPath(); overrides UseRawPath
r.UnescapePathValues = true // with raw or escaped matching, decode param valuesThis fragment sets every flag to its v1.12.0 default so the routing policy is visible in code review. UseEscapedPath is new in v1.12.0 and takes precedence over UseRawPath. Set these fields before the engine serves traffic: they are plain struct fields read on every request without locking, so changing them later is a data race.
Encoded slashes and raw paths
Go's url.URL stores both a decoded Path and, only when the client's encoding differs from the default one, a RawPath. A path such as /users/caf%C3%A9 has no RawPath, because that is exactly how Go would encode it, so it matches /users/:id and yields "café" with or without UseRawPath. /users/a%2Fb does record a RawPath. If identifiers can legitimately contain a slash, enable UseRawPath (or UseEscapedPath) and keep UnescapePathValues on, then validate the decoded value: a parameter that may contain '/' or '..' must never be joined into a file path or an upstream URL. If identifiers cannot contain a slash, the default 404 is the safer behavior.
Label metrics with FullPath and test with a table
c.FullPath() returns the registered template, such as /users/:id, and an empty string when nothing matched. That makes it the right label for request counters and latency histograms: /users/1 and /users/2 share one series. Labeling with c.Request.URL.Path creates a new time series per user, per typo and per scanner probe, which is how a metrics backend runs out of memory. Pin the routing contract with a table test of path, expected status, expected template and expected parameters, including one trailing-slash case, one empty-segment case and one encoded-slash case.
func routeLabel(c *gin.Context) string {
if route := c.FullPath(); route != "" {
return route // "/users/:id", never "/users/42"
}
return "unmatched" // 404s, 405s and trailing-slash probes share one series
}This helper is a fragment for your own metrics middleware: call it after c.Next() so the value reflects the matched route. An empty FullPath means the router found no handler, which covers 404 and 405 responses; collapsing them into one unmatched label keeps the cardinality bounded no matter what paths clients invent.
TAKE THIS WITH YOU
A :param is one non-empty segment and a *wildcard is the rest of the path; Gin rejects conflicting templates at boot, answers near-misses with redirects before middleware runs, and c.FullPath() gives the low-cardinality route label.
Check your understanding
A metrics middleware needs a low-cardinality route label. What does c.FullPath() give it?
Go to the source
Progress stays in this browser. No account needed.