https://github.com/posener/context
A proof of concept implementation of scoped context
https://github.com/posener/context
context go golang goroutine proof-of-concept scope
Last synced: 4 months ago
JSON representation
A proof of concept implementation of scoped context
- Host: GitHub
- URL: https://github.com/posener/context
- Owner: posener
- Created: 2018-09-22T13:08:26.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-04-13T16:57:37.000Z (almost 7 years ago)
- Last Synced: 2025-05-06T21:09:06.614Z (9 months ago)
- Topics: context, go, golang, goroutine, proof-of-concept, scope
- Language: Go
- Homepage: https://posener.github.io/goroutine-scoped-context
- Size: 19.5 KB
- Stars: 16
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# context
Package context is a proof of concept implementation of **scoped context**,
proposed in [this blog post](https://posener.github.io/goroutine-scoped-context).
This library should not be used for production code.
#### Usage
The context package should be imported from `github.com/posener/context`.
```diff
import (
- "context"
+ "github.com/posener/context"
)
```
Since this implementation does not involve changes to the runtime,
the goroutine context must be initialized.
```diff
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.
```diff
-func foo(ctx context.Context) {
+func foo() {
+ ctx := context.Get()
// Use context.
}
```
Applying context to a scope:
```go
unset := context.Set(ctx)
// ctx is applied until unset is called, or a deeper `Set` call.
unset()
```
Or:
```go
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:
```diff
-go foo()
+context.Go(foo)
```
More complected functions:
```diff
-go foo(1, "hello")
+context.Go(func() { foo(1, "hello") })
```
Running a goroutine with a new context:
```go
// `ctx` is the context that we want to have in the invoked goroutine
context.GoCtx(ctx, foo)
```
`context.TODO` should not be used anymore:
```diff
-f(context.TODO())
+f(context.Get())
```
## Sub Packages
* [runtime](./runtime)
---
Created by [goreadme](https://github.com/apps/goreadme)