Sharing data between handlers

Occasionally, we need to share a state between our middleware and handlers. Go 1.7 brought the context package into the standard library, which gives us, among other things, a way to share basic request-scoped data.

Every http.Request method comes with a context.Context object accessible via the request.Context() method, from which we can create new context objects. We can then call request.WithContext() to get a (cheap) shallow copied http.Request method that uses our new Context object.

To add a value, we can create a new context (based on the existing one from the request) via the context.WithValue method:

ctx := context.WithValue(r.Context(), "key", "value") 

Tip

While you can technically store any type of data using ...

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.