Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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