gorilla/mux · error
mux: route doesn't have a host
Error message
mux: route doesn't have a host
What it means
Returned by Route.URLHost (route.go:648-653) when building a URL but the route has no host matcher (r.regexp.host == nil). URLHost constructs only the host (and scheme), so a host matcher is mandatory. Route.URL() works without one and just returns the path.
Source
Thrown at route.go:653
queries = append(queries, query)
}
return &url.URL{
Scheme: scheme,
Host: host,
Path: path,
RawQuery: strings.Join(queries, "&"),
}, nil
}
// URLHost builds the host part of the URL for a route. See Route.URL().
//
// The route must have a host defined.
func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
if r.err != nil {
return nil, r.err
}
if r.regexp.host == nil {
return nil, errors.New("mux: route doesn't have a host")
}
values, err := r.prepareVars(pairs...)
if err != nil {
return nil, err
}
host, err := r.regexp.host.url(values)
if err != nil {
return nil, err
}
u := &url.URL{
Scheme: "http",
Host: host,
}
if r.buildScheme != "" {
u.Scheme = r.buildScheme
}
return u, nil
}View on GitHub (pinned to db9d1d0073)
Solutions
- Use Route.URL() if you only need the path (it tolerates a missing host).
- Add .Host(...) to the route definition before calling URLHost.
- Probe with GetHostTemplate() first; if it errors, fall back to URL().
Example fix
// before
u, err := r.Get("x").URLHost() // route has no Host
// after
u, err := r.Get("x").URL() // returns a path-only url Defensive patterns
Strategy: validation
Validate before calling
if _, err := rt.GetHostTemplate(); err != nil {
return rt.URL(pairs...) // path-only fallback
} Type guard
func hasHost(rt *mux.Route) bool { _, err := rt.GetHostTemplate(); return err == nil } Try / catch
u, err := rt.URLHost(pairs...)
if err != nil {
if strings.Contains(err.Error(), "host") {
u, err = rt.URL(pairs...)
}
} Prevention
- Prefer URL() unless you specifically need the host.
- Wrap URLHost callers with a hasHost probe.
- Document host-bearing routes.
When it happens
Trigger: r.NewRoute().Path("/x").Name("x"); then r.Get("x").URLHost(...) is called but Host() was never invoked on the route.
Common situations: Calling URLHost on a path-only route during link generation; refactor that removed a Host matcher but left URLHost callers; subrouter routes that inherit path but not host.
Related errors
- mux: route doesn't have a path
- key not found in metadata
- 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
AI-assisted analysis of gorilla/mux@db9d1d0073 (2026-08-04).
Data as JSON: /data/errors/52565a3794e3beea.json.
Report an issue: GitHub.