Skip to content

Commit

Permalink
add gohttp/app and http.HandlerFunc support
Browse files Browse the repository at this point in the history
  • Loading branch information
yields committed Nov 10, 2014
1 parent 7e00309 commit f4c5772
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
19 changes: 15 additions & 4 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
23 changes: 22 additions & 1 deletion mount.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
}
}

0 comments on commit f4c5772

Please sign in to comment.