Why I wrote gocraft/web
developer.uservoice.com34 pointsby cypriss15 comments
func (c *YourContext) UserRequired(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
user := userFromSession(r) // Pretend like this is defined. It reads a session cookie and returns a *User or nil.
if user != nil {
c.User = user
next(rw, r)
} else {
rw.Header().Set("Location", "/")
rw.WriteHeader(http.StatusMovedPermanently)
// do NOT call next()
}
}
Compatibility with Handler/HandlerFunc is kept at the top level, but not at every step along the middleware chain.
This library (Goji) solves it with a map[string]interface{}. This works, but has the downside that you need to type-assert your values from this map if you want to use them.
I wrote a library a while ago (http://www.github.com/gocraft/web) that uses reflection so that your contexts can be strongly typed. Martini offers a similar approach.