Documentation
¶
Overview ¶
Package contextprovider enables simpler context passing without requiring a change in function signature. It also enables localized and type-safe value passing ensuring access only to the functions needing them.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextValue ¶
ContextValue[T] is similar to InjectValue[T] except that you pass your own context
func FreeContext ¶
func FreeContext(funcs ...any)
FreeContext frees the context provided for zero or more receiver functions. Usually you'd use the free functions returned by Inject / InjectValue[T] so you free it after consumption but this is sort of an escape-hatch in case you have a usecase where you want to free the context much later after consumption.
func Inject ¶
Inject should be called in the context-receiving function and it returns the context provided for it. If there's no context provided for the function, context.Background() will be returned and ok will be false. The free function should be used to clear the context if it is no longer needed.
Example ¶
package main import ( "context" "fmt" "time" "github.com/AmitJoki/contextprovider" ) var timeoutInSeconds = 3 func main() { // This is a contrived example. You'd use top level functions in normal usage var provider, receiver func() receiver = func() { ctx, _, free := contextprovider.Inject() <-ctx.Done() fmt.Printf("Context cancelled after %v seconds", timeoutInSeconds) free() } provider = func() { ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutInSeconds)*time.Second) context.AfterFunc(ctx, cancel) // to satisfy https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/lostcancel contextprovider.Provide(ctx, receiver) } provider() receiver() }
Output: Context cancelled after 3 seconds
func InjectValue ¶
InjectValue[T] should be called in the context-value-receiving function and it returns the value of type T for the given key. If there's no key and/or no value of type T associated with the key, the zero value of T will be returned and ok will be false. The free function should be used to clear the context only if there are no more values/context to be consumed.
Example ¶
package main import ( "context" "fmt" "github.com/AmitJoki/contextprovider" ) type userKey string var loggedInKey userKey = "loggedInAt" var value = true func main() { // This is a contrived example. You'd use top level functions in normal usage var provider, receiver func() receiver = func() { loggedIn, _, free := contextprovider.InjectValue[bool](loggedInKey) fmt.Printf("Logged in: %v", loggedIn) free() } provider = func() { ctx := context.WithValue(context.Background(), loggedInKey, value) contextprovider.Provide(ctx, receiver) } provider() receiver() }
Output: Logged in: true
Types ¶
This section is empty.