package main import ( "context" "fmt" "log" ) func main() { ctx := context.WithValue(context.Background(), "requestID", "1234") logWithContext(ctx, "Hello world") } func logWithContext(ctx context.Context, message string) { requestID := ctx.Value("requestID").(string) log.Printf("[%s] %s", requestID, message) }
package main import ( "context" "fmt" ) func main() { parentCtx := context.WithValue(context.Background(), "userID", "user123") childCtx := context.WithValue(parentCtx, "itemName", "item456") printValues(parentCtx) printValues(childCtx) } func printValues(ctx context.Context) { userID := ctx.Value("userID").(string) itemName := ctx.Value("itemName") if itemName != nil { fmt.Printf("User %s is interested in item %s\n", userID, itemName.(string)) } else { fmt.Printf("User %s has no items of interest\n", userID) } }Both examples use the standard Go context package.