Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created July 27, 2025 21:04
Show Gist options
  • Save imjasonh/7fe17f9b7c8c3114e2be0b74fe62b07d to your computer and use it in GitHub Desktop.
Save imjasonh/7fe17f9b7c8c3114e2be0b74fe62b07d to your computer and use it in GitHub Desktop.
Generic Go context holder
package main
import "context"
type contextKey[T any] struct{}
func With[T any](ctx context.Context, t T) context.Context {
var k contextKey[T]
return context.WithValue(ctx, k, t)
}
func Get[T any](ctx context.Context) (T, bool) {
var k contextKey[T]
val, ok := ctx.Value(k).(T)
return val, ok
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment