From db7dbe32aa449d64194f811d532c9d3fcc5c3255 Mon Sep 17 00:00:00 2001 From: Christian Himpel Date: Fri, 31 Aug 2012 12:00:01 -0400 Subject: [PATCH] net/http: fix inserting of implicit redirects in serve mux In serve mux, if pattern contains a host name, pass only the path to the redirect handler. Add tests for serve mux redirections. R=rsc CC=bradfitz, gobot, golang-dev https://golang.org/cl/6329045 --- src/pkg/net/http/serve_test.go | 19 ++++++++++++++++--- src/pkg/net/http/server.go | 10 +++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/pkg/net/http/serve_test.go b/src/pkg/net/http/serve_test.go index 17b7566b38..c5cf6ae711 100644 --- a/src/pkg/net/http/serve_test.go +++ b/src/pkg/net/http/serve_test.go @@ -173,6 +173,9 @@ var vtests = []struct { {"http://someHost.com/someDir/apage", "someHost.com/someDir"}, {"http://otherHost.com/someDir/apage", "someDir"}, {"http://otherHost.com/aDir/apage", "Default"}, + // redirections for trees + {"http://localhost/someDir", "/someDir/"}, + {"http://someHost.com/someDir", "/someDir/"}, } func TestHostHandlers(t *testing.T) { @@ -204,9 +207,19 @@ func TestHostHandlers(t *testing.T) { t.Errorf("reading response: %v", err) continue } - s := r.Header.Get("Result") - if s != vt.expected { - t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) + switch r.StatusCode { + case StatusOK: + s := r.Header.Get("Result") + if s != vt.expected { + t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) + } + case StatusMovedPermanently: + s := r.Header.Get("Location") + if s != vt.expected { + t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) + } + default: + t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode) } } } diff --git a/src/pkg/net/http/server.go b/src/pkg/net/http/server.go index 272c8408c7..bac5faed1b 100644 --- a/src/pkg/net/http/server.go +++ b/src/pkg/net/http/server.go @@ -997,7 +997,15 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) { // It can be overridden by an explicit registration. n := len(pattern) if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit { - mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(pattern, StatusMovedPermanently)} + // If pattern contains a host name, strip it and use remaining + // path for redirect. + path := pattern + if pattern[0] != '/' { + // In pattern, at least the last character is a '/', so + // strings.Index can't be -1. + path = pattern[strings.Index(pattern, "/"):] + } + mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(path, StatusMovedPermanently)} } } -- 2.48.1