Created
August 6, 2024 04:51
-
-
Save CAFxX/446c912dbf29595f44451baf69232e77 to your computer and use it in GitHub Desktop.
context.WithValueFunc(...)
This file contains 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 context | |
import ( | |
"context" | |
"sync" | |
) | |
func WithValueFunc(ctx context.Context, key any, valFn func() any) context.Context { | |
return &valFunc{Context: ctx, key: key, valFn: valFn} | |
} | |
type valFunc struct { | |
context.Context | |
key any | |
once sync.Once | |
valFn func() any | |
val any | |
} | |
var _ context.Context = &valFunc{} | |
func (v *valFunc) Value(key any) any { | |
if key != v.key { | |
return v.Context.Value(key) | |
} | |
v.once.Do(func() { | |
v.val = v.valFn() | |
v.valFn = nil | |
}) | |
return v.val | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment