Created
July 27, 2025 21:04
-
-
Save imjasonh/7fe17f9b7c8c3114e2be0b74fe62b07d to your computer and use it in GitHub Desktop.
Generic Go context holder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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