June 2017
Beginner
1091 pages
22h 9m
English
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")
While you can technically store any type of data using ...
Read now
Unlock full access