Integrating Golang.org/x/net/context with Negroni

Update: It looks like net/context will now be attached to net/http.Request in Go1.7_early. So, its probably better to stick to negroni + gorilla for development. And wait for Go1.7 to be released. For those who are interested, have a look at:

https://github.com/golang/go/issues/14660
https://go-review.googlesource.com/#/c21496

 

Original post as follows:

Golang feels pretty neat and recently I’ve been trying to learn more by developing a webapp. So far, I have tested a fair of bootstrap approaches including beego/gorilla/goji/etc, but I prefer a light-weight approach that looks like negroni + gorilla/mux. Trouble is, I now need to use gorilla/context to manage context, but having a singleton gorilla/context map bothers me.

Truth is, I really like negroni because its small, and the code is well-designed. However, I think being able to pass context information through middleware handlers (for authentication purposes/etc) is a big plus.

So how can you use golang.org/x/net/context to serve the context?

A context adapter like https://bitbucket.org/pbgc/nctx/overview, doesn’t make the cut. Primarily, its because context is an interface and it passes by value.

Over the weekend, I tried to integrate golang.org/x/net/context into negroni. Now I have an implementation of negroni that uses a handler signature like this:

I have also forked both httprouter & gorilla/mux to test out this model.

https://github.com/haxgo/hax
https://github.com/haxgo/muxc
https://github.com/haxgo/httpcrouter

So I’m using a hax (negroni)/muxc (gorilla/mux) combination that utilizes golang.org/x/net/context. They work pretty fine like they used to albeit with a different handler. Test cases are doing well. The objective to store values in middlewareA, and retrieve them from middlewareB, and downstream handlers, has been met.

This is really useful for authentication. I’m not sure if there will be tricky racy conditions right now, but hopefully it will be manageable.

Looking for more feedback on this approach.

Leave a Reply

Your email address will not be published. Required fields are marked *