From: Brad Fitzpatrick Date: Mon, 18 Mar 2013 20:44:20 +0000 (-0700) Subject: net/http: add StripPrefix example; simplify code X-Git-Tag: go1.1rc2~458 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=725519902f005260f55c6248fdc70d890d754fdb;p=gostls13.git net/http: add StripPrefix example; simplify code The example is the same as the FileServer one, but it's relevant for both. Also use strings.TrimPrefix while I'm here. R=golang-dev, rsc CC=golang-dev https://golang.org/cl/7598046 --- diff --git a/src/pkg/net/http/example_test.go b/src/pkg/net/http/example_test.go index 22073eaf7a..eed3beeea3 100644 --- a/src/pkg/net/http/example_test.go +++ b/src/pkg/net/http/example_test.go @@ -54,3 +54,8 @@ func ExampleFileServer() { // we use StripPrefix so that /tmpfiles/somefile will access /tmp/somefile http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) } + +func ExampleStripPrefix() { + // we use StripPrefix so that /tmpfiles/somefile will access /tmp/somefile + http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) +} diff --git a/src/pkg/net/http/server.go b/src/pkg/net/http/server.go index 9021767163..5086ad0a79 100644 --- a/src/pkg/net/http/server.go +++ b/src/pkg/net/http/server.go @@ -948,13 +948,16 @@ func NotFoundHandler() Handler { return HandlerFunc(NotFound) } // request for a path that doesn't begin with prefix by // replying with an HTTP 404 not found error. func StripPrefix(prefix string, h Handler) Handler { + if prefix == "" { + return h + } return HandlerFunc(func(w ResponseWriter, r *Request) { - if !strings.HasPrefix(r.URL.Path, prefix) { + if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) { + r.URL.Path = p + h.ServeHTTP(w, r) + } else { NotFound(w, r) - return } - r.URL.Path = r.URL.Path[len(prefix):] - h.ServeHTTP(w, r) }) }