Skip to content

posener/context

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

context

Package context is a proof of concept implementation of scoped context, proposed in this blog post.

This library should not be used for production code.

Usage

The context package should be imported from github.com/posener/context.

 import (
-   "context"
+   "github.com/posener/context"
 )

Since this implementation does not involve changes to the runtime, the goroutine context must be initialized.

 func main() {
+	context.Init()
 	// Go code goes here.
 }

Functions should not anymore receive the context in the first argument. They should get it from the goroutine scope.

-func foo(ctx context.Context) {
+func foo() {
+	ctx := context.Get()
 	// Use context.
 }

Applying context to a scope:

unset := context.Set(ctx)
// ctx is applied until unset is called, or a deeper `Set` call.
unset()

Or:

defer context.Set(ctx)()
// ctx is applied until the end of the function or a deeper `Set` call.

Invoking goroutines should be done with context.Go or context.GoCtx

Running a new goroutine with the current stored context:

-go foo()
+context.Go(foo)

More complected functions:

-go foo(1, "hello")
+context.Go(func() { foo(1, "hello") })

Running a goroutine with a new context:

// `ctx` is the context that we want to have in the invoked goroutine
context.GoCtx(ctx, foo)

context.TODO should not be used anymore:

-f(context.TODO())
+f(context.Get())

Sub Packages


Created by goreadme

Releases

No releases published

Packages

No packages published

Languages