https://github.com/contextplus/contextplus
Package contextplus provide more easy to use functions for contexts.
https://github.com/contextplus/contextplus
context golang
Last synced: 12 months ago
JSON representation
Package contextplus provide more easy to use functions for contexts.
- Host: GitHub
- URL: https://github.com/contextplus/contextplus
- Owner: contextplus
- License: mit
- Created: 2022-09-23T02:38:15.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-03-20T02:47:26.000Z (almost 3 years ago)
- Last Synced: 2024-07-31T20:53:32.825Z (over 1 year ago)
- Topics: context, golang
- Language: Go
- Homepage:
- Size: 5.86 KB
- Stars: 16
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-go - contextplus - Package contextplus provide more easy to use functions for contexts. (Utilities / Utility/Miscellaneous)
- awesome-go-cn - contextplus
- awesome-go - contextplus - Package contextplus provide more easy to use functions for contexts. (Utilities / Utility/Miscellaneous)
- awesome-go - contextplus - Package contextplus provide more easy to use functions for contexts. (Utilities / Utility/Miscellaneous)
README
[](https://goreportcard.com/report/github.com/contextplus/contextplus)
[](https://pkg.go.dev/github.com/contextplus/contextplus)
[](https://github.com/contextplus/contextplus/actions/workflows/test.yaml)
[](https://codecov.io/gh/contextplus/contextplus)
[](https://github.com/avelino/awesome-go)
# contextplus
Package contextplus provide more easy to use functions for contexts.
# Use
```
go get -u github.com/contextplus/contextplus
```
# Example
This is how an http.Handler should run a goroutine that need values from the context. Pretend to use the middleware that timeout after one second.
```golang
func myMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx, cancel := context.WithTimeout(time.Second)
defer cancel()
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
```
```golang
func handle(w http.ResponseWriter, r *http.Request) {
asyncCtx := contextplus.WithOnlyValue(r.Context())
go func() {
// will not cancel if timeout
// will not cancel if call 'cancel'
asyncTask(asyncCtx)
}()
}
```
```golang
func handle(w http.ResponseWriter, r *http.Request) {
asyncCtx := contextplus.WithoutCancel(r.Context())
go func() {
// will cancel if timeout
// will not cancel if call 'cancel'
asyncTask(asyncCtx)
}()
}
```