Last active
August 29, 2015 14:01
-
-
Save emrekzd/3d610cfccbdc795eb412 to your computer and use it in GitHub Desktop.
Chaining http handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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