Finally some context: Request scoped state in Go 1.7

Mat Ryer
2 min readJul 9, 2016

--

EDIT —Peter Bourgon has provided a much neater example for this blog post.

The times they are indeed a-changing. net/context is moving into the standard library as context.

I might be a little too excited about this:

This means no more hacking to share context objects between http.Handler types.

Instead, you update the context as you did before (for example using WithValue) and call WithContext on the http.Request to get a new (shallow copied) Request containing the new context, which you then pass into other handlers without changing the (w http.ResponseWriter, r *http.Request) interface.

Example

Peter Bourgon put together a simple example to show off how state can be shared using context in Go 1.7.

In this example, the auth token is made available to wrapped handlers via the context.

context.WithValue creates a new context with the specified key/value pair, and for the first time we are able to pass in the context that already exists in the Request via the new Context() method on line 23. This means that the WithAuth function can focus entirely on its job even knowing what else is going on inside the context object.

Once the new context is ready, execution passes (on line 24) to the next handler with a new Request object that contains the new context via Request.WithContext; another new method that comes to us in Go 1.7.

Finally, the Request.Context() method is called inside the handler to access the auth token.

Sharing state isn’t all you can do with Context, and it is well worth spending some time with Sameer Ajmani on Go Concurrency Patterns with Context to explore its full potential.

--

--

Mat Ryer

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints