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
This commit is contained in:
Brad Fitzpatrick 2013-03-18 13:44:20 -07:00
parent c668715334
commit 725519902f
2 changed files with 12 additions and 4 deletions

View 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"))))
}

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