From 725519902f005260f55c6248fdc70d890d754fdb Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Mon, 18 Mar 2013 13:44:20 -0700 Subject: [PATCH] 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 --- src/pkg/net/http/example_test.go | 5 +++++ src/pkg/net/http/server.go | 11 +++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) 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) }) } -- 2.50.0