1
0
mirror of https://github.com/golang/go synced 2024-11-24 22:00:09 -07:00

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
This commit is contained in:
Christian Himpel 2012-08-31 12:00:01 -04:00 committed by Russ Cox
parent d073677569
commit db7dbe32aa
2 changed files with 25 additions and 4 deletions

View File

@ -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)
}
}
}

View File

@ -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)}
}
}