Skip to content

Commit

Permalink
Add ConstructorFunc / MiddlewareFunc
Browse files Browse the repository at this point in the history
MiddlewareFunc defines a standard signature for a http.HandlerFunc which
accepts a chained http.Handler to invoke. ConstructorFunc supplies an
adapter for converting a MiddlewareFunc into a Constructor. This is most
useful for building middleware with bound parameters via closures.
  • Loading branch information
Johnny Graettinger committed Jul 31, 2016
1 parent 8f06f31 commit 8f8931b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
24 changes: 24 additions & 0 deletions chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,30 @@ import "net/http"
// so in most cases you can just pass somepackage.New
type Constructor func(http.Handler) http.Handler

// A MiddlewareFunc performs a middleware action, and then passes
// control to the supplied http.Handler
type MiddlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)

// ConstructorFunc adapts a MiddlewareFunc to be used as a Constructor.
// This simplifies the use of closures to construct middleware with bound
// parameters. Eg:
// func AddHeader(key, value string) Constructor {
// var h = func(w http.ResponseWriter, r *http.Request, next http.Handler) {
// w.Header().Add(key, value)
// next.ServeHTTP(w, r)
// }
// return ConstructorFunc(h)
// }
func ConstructorFunc(f MiddlewareFunc) Constructor {
return f.construct
}

func (f MiddlewareFunc) construct(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f(w, r, next)
})
}

// Chain acts as a list of http.Handler constructors.
// Chain is effectively immutable:
// once created, it will always hold
Expand Down
9 changes: 4 additions & 5 deletions chain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ import (
// that writes its own "tag" into the RW and does nothing else.
// Useful in checking if a chain is behaving in the right order.
func tagMiddleware(tag string) Constructor {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(tag))
h.ServeHTTP(w, r)
})
var h = func(w http.ResponseWriter, r *http.Request, next http.Handler) {
w.Write([]byte(tag))
next.ServeHTTP(w, r)
}
return ConstructorFunc(h)
}

// Not recommended (https://golang.org/pkg/reflect/#Value.Pointer),
Expand Down

0 comments on commit 8f8931b

Please sign in to comment.