Commit 72551990 authored by Brad Fitzpatrick's avatar Brad Fitzpatrick

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
parent c6687153
......@@ -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"))))
}
......@@ -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)
})
}
......
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