{
  "path": "/posts/2018/2018-04-06-go-context",
  "site": "at://did:plc:mracrip6qu3vw46nbewg44sm/site.standard.publication/self",
  "tags": [
    "code",
    "go"
  ],
  "$type": "site.standard.document",
  "title": "Tracking a call stack in Go with context",
  "updatedAt": "2018-04-06T21:00:00.000Z",
  "publishedAt": "2018-04-06T21:00:00.000Z",
  "textContent": "The use of context in Go can help you pass metadata through your program with helpful, related information about a call.\nLet's build an example where we set a context key, \"stack\", which keeps a history of the function names called over the lifetime of the context.\nAs we pass the context object through a few layers of functions, we'll append the name of the function to the value of the context key \"stack\".\n\n<https://play.golang.org/p/Q-2AmWQ-bf6>\n\nIn the code above, we initialize an empty context in our main function, then pass it down into some methods: Handler, Service and Gateway respectively.\nIn Gateway, we print the final value of the \"stack\" key on the context object, which is Handler:Service:Gateway.\nYou'll notice we've had to hardcode the names of the functions ourselves which are appended to the \"stack\" context variable when we explicitly pass them into buildStackContext.\nHowever, we can improve this.\nBy inspecting the Go runtime, we can programmatically look up the name of the function that calls buildStackContext and append that to the \"stack\" variable in the context:\n\n<https://play.golang.org/p/AXOPYBr5SKF>\n\nThe above code yields the same output, Handler:Service:Gateway, but it allows us to arbitrarily add more function calls or change function names and still get the expected stack of function calls:\n\n<https://play.golang.org/p/Eb8eZ5AfWke>\n\nThe above prints: Consumer:Service:Gateway:Client.\nUsing context in this way can provide useful namespacing in logs, making it easier to distinguish homogeneous log statements.",
  "canonicalUrl": "https://www.danielcorin.com/posts/2018/2018-04-06-go-context"
}