https://github.com/knwoop/dcontext
Copy context.Context without setting timeout in one
https://github.com/knwoop/dcontext
Last synced: about 1 year ago
JSON representation
Copy context.Context without setting timeout in one
- Host: GitHub
- URL: https://github.com/knwoop/dcontext
- Owner: knwoop
- License: mit
- Created: 2021-12-21T01:20:07.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-05-24T01:00:36.000Z (about 4 years ago)
- Last Synced: 2025-04-01T23:40:25.741Z (over 1 year ago)
- Language: Go
- Size: 11.7 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# dcontext
Copy context.Context without setting timeout
## Set up
```bash
$ go get -u github.com/knwoop/dcontext
```
## Example
```go
package main
import (
"context"
"fmt"
"time"
"github.com/knwoop/dcontext"
)
func main() {
parentCtx := context.Background()
parentCtx = context.WithValue(parentCtx, "trace-id", "trace123")
ctx, cancel := context.WithCancel(parentCtx)
// detatch context
dtx := dcontext.Detach(ctx)
// Cancel context
cancel()
fmt.Println("dtx.Err():", dtx.Err())
fmt.Println(`dtx.Value("trace-id"):`, dtx.Value("trace-id"))
// Create a child context with a deadline.
ttx, cancel := context.WithTimeout(dtx, time.Millisecond)
cancel()
deadline, ok := ttx.Deadline()
fmt.Println("ttx.Deadline():", deadline, ok)
fmt.Println("ttx.Err():", ttx.Err())
fmt.Println(`ttx.Value("trace-id"):`, ttx.Value("trace-id"))
}
```
## Reference
https://zenn.dev/knwoop/articles/dd93fffb48775b