Skip to content

Instantly share code, notes, and snippets.

@emrekzd
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emrekzd/3d610cfccbdc795eb412 to your computer and use it in GitHub Desktop.
Save emrekzd/3d610cfccbdc795eb412 to your computer and use it in GitHub Desktop.
Chaining http handlers
package chain
import (
"net/http"
)
type Chain handlerFunc
type handlerFunc func(http.ResponseWriter, *http.Request)
func NewChain(handlers ...handlerFunc) Chain {
if handlers == nil || len(handlers) == 0 {
panic("no handlers were passed")
}
var c Chain
for _, h := range handlers {
if h == nil {
panic("nil handler")
}
c = c.add(h)
}
return c
}
func (c Chain) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c(w, r)
}
func (c Chain) add(f handlerFunc) Chain {
return func(w http.ResponseWriter, r *http.Request) {
if c != nil {
c(w, r)
}
f(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment