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.
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
To add a value, we can create a new context (based on the existing one from the request) via the
ctx := context.WithValue(r.Context(), "key", "value")
While you can technically store any type of data using ...