]> Cypherpunks repositories - gostls13.git/commitdiff
net/http: add StripPrefix example; simplify code
authorBrad Fitzpatrick <bradfitz@golang.org>
Mon, 18 Mar 2013 20:44:20 +0000 (13:44 -0700)
committerBrad Fitzpatrick <bradfitz@golang.org>
Mon, 18 Mar 2013 20:44:20 +0000 (13:44 -0700)
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
src/pkg/net/http/server.go

index 22073eaf7aa88fba065e64f96d4bfcfdd17adcec..eed3beeea31a4c9c1d7d374d7f677bd017fb08cd 100644 (file)
@@ -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"))))
+}
index 902176716322a2189a9a636e27fb0cd23e68f78e..5086ad0a7936c10b96745782071e269802979cb7 100644 (file)
@@ -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)
        })
 }