diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..e7970d5 --- /dev/null +++ b/Readme.md @@ -0,0 +1,10 @@ + +# mount + + Mount middleware. Pretty much just http.StripPrefix but still invokes the upstream. + + View the [docs](http://godoc.org/github.com/gohttp/mount). + +# License + + MIT \ No newline at end of file diff --git a/examples/main.go b/examples/main.go new file mode 100644 index 0000000..37c4911 --- /dev/null +++ b/examples/main.go @@ -0,0 +1,20 @@ +package main + +import "github.com/gohttp/logger" +import "github.com/gohttp/serve" +import "github.com/gohttp/mount" +import "github.com/gohttp/app" +import "net/http" + +func main() { + a := app.New() + + a.Use(logger.New()) + a.Use(mount.New("/examples", serve.New("examples"))) + + a.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("hello")) + })) + + a.Listen(":3000") +} diff --git a/mount.go b/mount.go new file mode 100644 index 0000000..345b7c5 --- /dev/null +++ b/mount.go @@ -0,0 +1,24 @@ +package mount + +import "net/http" +import "strings" + +// Middleware constructor. +type Constructor func(http.Handler) http.Handler + +// New mount middleware. +func New(prefix string, mw Constructor) func(http.Handler) http.Handler { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + original := r.URL.Path + + if s := strings.TrimPrefix(r.URL.Path, prefix); len(s) < len(r.URL.Path) { + r.URL.Path = s + mw(h).ServeHTTP(w, r) + r.URL.Path = original + } else { + h.ServeHTTP(w, r) + } + }) + } +}