Skip to content

Instantly share code, notes, and snippets.

@CAFxX
Created August 6, 2024 04:51
Show Gist options
  • Save CAFxX/446c912dbf29595f44451baf69232e77 to your computer and use it in GitHub Desktop.
Save CAFxX/446c912dbf29595f44451baf69232e77 to your computer and use it in GitHub Desktop.
context.WithValueFunc(...)
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