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 this approach, it is only recommended that you store simple primitive types such as Strings and Integers and do not use it to inject dependencies or pointers to other objects that your handlers might need. Later in this chapter, we will explore...