Storing values in a context is quite flexible, but comes without strict type safety, and obscures the API. So what can we do about this?
First, for type safety, we’re limited to runtime assertions:
userID := ctx.Value(userIDKey).(string)
But this can panic if we ever get an unexpected value (or even nil
). So to make it safer, we can use the two-variable assignment form, which yields a bool indicating success:
userID, ok := ctx.Value(userIDKey).(string)
if !ok {
return errors.New("userID not found in context")
}
But for the obscure API problem, what can we do?
This may be anti-climactic, but the best solution I’ve found is to simply avoid using context values. Of course that’s not always practical, so it means we have to choose between trade-offs.
But this brings me finally to answer the question: Should request-scoped “access objects” be included in a context?
My answer: No.
Don’t pass a logger, database handle, or other such object, even when specifically configured per request, via context, unless there’s really no other way. Instead, my advice, is to pass them to an object constructor, then pass your context to a method.
Let me illustrate.
Don’t do this:
func Foo(ctx context.Context, /* ... */) {
logger := ctx.Value(loggerKey).(*slog.Logger)
logger.Info(/* ... */)
/* ... */
}
Instead do this:
type Controller struct {
logger *slog.Logger
}
func New(logger *slog.Logger) Controller {
return Controller{logger: logger}
}
func (c *Controller) Foo(ctx context.Context, /* ... */) {
c.logger.Info(/* ... */)
}
It’s a bit more verbose in this simple case, but it makes the API explicit, and it provides compile-time type safety. There’s no risk of receiving a nil logger.
This particular approach doesn’t actually solve the issue of propagating a request-scoped logger, however. Addressing that issue is more involved than I can fully address today. It’s also well beyond the scope of the context
package, which is itself a clue to the answer: It’s rare to actually need request-scoped loggers (or databases, or other objects). There’s probably a better way. (If you need help finding that better way, feel free to send me an email, and I can talk about it in an upcoming email.)