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 Jun 22, 2016
1 parent 8f06f31 commit d6e1832
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,31 @@ 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 {
var h = func(w http.ResponseWriter, r *http.Request) {
f(w, r, next)
}
return http.HandlerFunc(h)
}

// Chain acts as a list of http.Handler constructors.
// Chain is effectively immutable:
// once created, it will always hold
Expand Down

0 comments on commit d6e1832

Please sign in to comment.