gorilla/mux · error
mux: path must start with a slash, got %q
Error message
mux: path must start with a slash, got %q
What it means
Returned by addRegexpMatcher (route.go:251-253) when a Path or PathPrefix template is non-empty and does not begin with '/'. Path matchers require absolute paths; relative or scheme-prefixed strings are rejected. The error is stored on r.err, disabling the route.
Source
Thrown at route.go:253
Match(*http.Request, *RouteMatch) bool
}
// addMatcher adds a matcher to the route.
func (r *Route) addMatcher(m matcher) *Route {
if r.err == nil {
r.matchers = append(r.matchers, m)
}
return r
}
// addRegexpMatcher adds a host or path matcher and builder to a route.
func (r *Route) addRegexpMatcher(tpl string, typ regexpType) error {
if r.err != nil {
return r.err
}
if typ == regexpTypePath || typ == regexpTypePrefix {
if len(tpl) > 0 && tpl[0] != '/' {
return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
}
if r.regexp.path != nil {
tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
}
}
rr, err := newRouteRegexp(tpl, typ, routeRegexpOptions{
strictSlash: r.strictSlash,
useEncodedPath: r.useEncodedPath,
})
if err != nil {
return err
}
for _, q := range r.regexp.queries {
if err = uniqueVars(rr.varsN, q.varsN); err != nil {
return err
}
}
if typ == regexpTypeHost {View on GitHub (pinned to db9d1d0073)
Solutions
- Prefix the template with '/'.
- For PathPrefix, include the leading slash and usually a trailing slash (e.g. "/api/").
- Normalize user-supplied path config before registering routes.
Example fix
// before
r.Path("users/{id}")
// -> mux: path must start with a slash, got "users/{id}"
// after
r.Path("/users/{id}") Defensive patterns
Strategy: validation
Validate before calling
func ensureSlash(tpl string) string {
if tpl != "" && !strings.HasPrefix(tpl, "/") { return "/" + tpl }
return tpl
} Type guard
func validPathTpl(tpl string) bool { return tpl == "" || strings.HasPrefix(tpl, "/") } Try / catch
rt := r.Path(tpl)
if err := rt.GetError(); err != nil {
return fmt.Errorf("bad path %q: %w", tpl, err)
} Prevention
- Normalize config-driven paths with ensureSlash before Path().
- Always use PathPrefix("/...") with a leading slash.
- Unit-test route construction.
When it happens
Trigger: r.Path("users/{id}") (no leading slash); r.PathPrefix("api/"); passing a full URL like "http://host/users" to Path.
Common situations: Treating mux paths like Express/Flask (no leading slash); concatenating a base path without ensuring a leading slash; passing the full URL instead of just the path.
Related errors
- mux: duplicated route variable %q
- mux: number of parameters must be multiple of 2, got %v
- mux: route already has name %q, can't set %q
- mux: number of parameters must be multiple of 2, got %v
- mux: missing name or pattern in %q
AI-assisted analysis of gorilla/mux@db9d1d0073 (2026-08-04).
Data as JSON: /data/errors/853172e04422974c.json.
Report an issue: GitHub.