diff --git a/mux.go b/mux.go index b6c06fd2..72d415a0 100644 --- a/mux.go +++ b/mux.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "net/http" + "net/url" "path" "regexp" ) @@ -180,15 +181,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { } // Clean path to canonical form and redirect. if p := cleanPath(path); p != path { - - // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. - // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: - // http://code.google.com/p/go/issues/detail?id=5252 - url := *req.URL - url.Path = p - p = url.String() - - w.Header().Set("Location", p) + w.Header().Set("Location", replaceURLPath(req.URL, p)) w.WriteHeader(http.StatusMovedPermanently) return } @@ -488,6 +481,14 @@ func cleanPath(p string) string { return np } +// replaceURLPath prints an url.URL with a different path. +func replaceURLPath(u *url.URL, p string) string { + // Operate on a copy of the request url. + u2 := *u + u2.Path = p + return u2.String() +} + // uniqueVars returns an error if two slices contain duplicated strings. func uniqueVars(s1, s2 []string) error { for _, v1 := range s1 { diff --git a/regexp.go b/regexp.go index 185ae26f..b577073f 100644 --- a/regexp.go +++ b/regexp.go @@ -355,13 +355,14 @@ func (v routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { p1 := strings.HasSuffix(path, "/") p2 := strings.HasSuffix(v.path.template, "/") if p1 != p2 { - u, _ := url.Parse(req.URL.String()) + p := req.URL.Path if p1 { - u.Path = u.Path[:len(u.Path)-1] + p = p[:len(p)-1] } else { - u.Path += "/" + p += "/" } - m.Handler = http.RedirectHandler(u.String(), http.StatusMovedPermanently) + u := replaceURLPath(req.URL, p) + m.Handler = http.RedirectHandler(u, http.StatusMovedPermanently) } } }