From eb08516a5e001c25761b0df161a3205f545a45cd Mon Sep 17 00:00:00 2001 From: Carl Jackson Date: Sun, 27 Apr 2014 00:54:29 +0200 Subject: [PATCH] EnvInit middleware Provide a standard middleware to set c.Env. Don't include it in the default stack, however, since the RequestID middleware will end up allocating Env anyways. Fixes #11 --- web/middleware/envinit.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 web/middleware/envinit.go diff --git a/web/middleware/envinit.go b/web/middleware/envinit.go new file mode 100644 index 0000000..aefefb7 --- /dev/null +++ b/web/middleware/envinit.go @@ -0,0 +1,26 @@ +package middleware + +import ( + "net/http" + + "github.com/zenazn/goji/web" +) + +// EnvInit is a middleware that allocates an environment map if one does not +// already exist. This is necessary because Goji does not guarantee that Env is +// present when running middleware (it avoids forcing the map allocation). Note +// that other middleware should check Env for nil in order to maximize +// compatibility (when EnvInit is not used, or when another middleware layer +// blanks out Env), but for situations in which the user controls the middleware +// stack and knows EnvInit is present, this middleware can eliminate a lot of +// boilerplate. +func EnvInit(c *web.C, h http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + if c.Env == nil { + c.Env = make(map[string]interface{}) + } + h.ServeHTTP(w, r) + } + + return http.HandlerFunc(fn) +}