gctx: a new package for a goroutine-local context

130 views
Skip to first unread message

Sven Anderson

unread,
Feb 23, 2022, 2:01:24 PM2/23/22
to golan...@googlegroups.com
Dear all,

TL;DR
Set a goroutine context with gctx.Set(ctx) and retrieve it from anywhere in the same or a child goroutine with gctx.Get(): https://github.com/ansiwen/gctx

This topic has been discussed many times already here and in issues. Go intentionally doesn't offer a way to identify the current goroutine. There are good reasons for that decision. But there are sometimes also good reasons for having some kind of goroutine-local context. Thats why there have been a couple of workarounds, but they didn't work too well and seem to be abandoned.

I recently was thinking about how to add context-aware debug logging in a library and found myself in the same situation as many others before. Because there didn’t seem to be a maintained library that solved that problem, I looked into it myself and eventually found an efficient and relatively "stable" way to store a context in the goroutine-local storage, by piggybacking it onto the profiling labels. (It’s still a hack of course, but I hope less than the previous gls attempts.)

Given the frequent reoccurrence of the topic, I guess it could be useful to others as well so I wrapped it up in a small module. (see above) Feedback as always appreciated.


Sven (@ansiwen)

Reply all
Reply to author
Forward
0 new messages