Commit db7dbe32 authored by Christian Himpel's avatar Christian Himpel Committed by Russ Cox

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
parent d0736775
......@@ -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)
}
}
}
......
......@@ -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)}
}
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment