Using context for passing request-scoped data
Request-scoped objects are those that are created when request processing starts and discarded when request processing ends. These are usually lightweight objects, such as a request identifier, authentication information identifying the caller, or loggers. In this section, you will see how these objects can be passed around using a context.
How to do it...
The idiomatic way of adding data values to a context is as follows:
- Define a context key type. This avoids accidental name collisions. The use of an unexported type name such as the following is common. This pattern limits the ability to put or get context values of this particular type to the current package:
type requestIDKeyType int
Warning
You might be tempted to use struct{}
instead of int
here. After all, struct{}
does not consume any additional memory. You have to be very careful when working with 0-size structures as the Go language specification does not...