chaining contexts, best practices question

58 views
Skip to first unread message

Josh Humphries

unread,
Aug 8, 2017, 10:50:04 AM8/8/17
to golang-nuts
I noticed the Go doc for context.Context includes the following snippet:

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it.

I think one potential reason for going against this advice is maintaining context chain relationships in servers. In a server object, it seems reasonable to provide a context when starting the server (which is valid for the lifetime the server is serving) and the server to then store that context in a struct. The reason it would be stored is that it could be used to create child contexts when handling incoming data from the socket (or whatever the server does).

The reason I would do this is two-fold:
  1. It is convenient and IMO elegant (particularly, but not exclusively, in test code) to be able to simply cancel a top-level context and have that respected throughout the chain, resulting in the server stopping and tearing itself down.
  2. It is a natural place for server-scoped contextual data. For example, we use a log library that allows log writer configuration to be stored in context. We could configure the log writer once for the server and have it then correctly applied to every action taken by the server, including request dispatches.
Does this seem like a reasonable approach, or are there other possibly better practices for addressing these issues?

Obviously we must do things differently for HTTP and GRPC servers since those libraries do not expose a way to provide a "parent context" for the whole server. In those cases, we provide a method for registering HTTP handlers that will wrap an incoming handler with one that decorates the request context (for bullet #2 above; and we can use interceptors for GRPC). For bullet #1, we have to implement our own cancellation propagation -- like a goroutine that will stop the server(s) when the root context gets cancelled.

I'm curious how others tackle these kinds of concerns.

----
Josh Humphries
jh...@bluegosling.com
Reply all
Reply to author
Forward
0 new messages