diff --git a/examples/main.go b/examples/main.go index 37c4911..8236687 100644 --- a/examples/main.go +++ b/examples/main.go @@ -11,10 +11,21 @@ func main() { 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.Use(mount.New("/blog", blog())) + a.Use(mount.New("/hello", hello)) + a.Get("/", http.HandlerFunc(hello)) a.Listen(":3000") } + +func blog() *app.App { + app := app.New() + app.Get("", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("posts\n")) + }) + return app +} + +func hello(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("hello\n")) +} diff --git a/mount.go b/mount.go index 345b7c5..7c43dae 100644 --- a/mount.go +++ b/mount.go @@ -7,7 +7,8 @@ import "strings" type Constructor func(http.Handler) http.Handler // New mount middleware. -func New(prefix string, mw Constructor) func(http.Handler) http.Handler { +func New(prefix string, i interface{}) func(http.Handler) http.Handler { + mw := middleware(i) return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { original := r.URL.Path @@ -22,3 +23,23 @@ func New(prefix string, mw Constructor) func(http.Handler) http.Handler { }) } } + +// Coerce into middleware. +func middleware(h interface{}) func(http.Handler) http.Handler { + switch h.(type) { + case func(w http.ResponseWriter, r *http.Request): + h := http.HandlerFunc(h.(func(w http.ResponseWriter, r *http.Request))) + return func(_ http.Handler) http.Handler { + return http.HandlerFunc(h) + } + case http.Handler: + h := h.(http.Handler) + return func(_ http.Handler) http.Handler { + return h + } + case func(h http.Handler) http.Handler: + return h.(func(h http.Handler) http.Handler) + default: + panic("invalid middleware") + } +}