Skip to content

Copy context.Context without setting timeout in one

License

Notifications You must be signed in to change notification settings

knwoop/dcontext

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 

Repository files navigation

dcontext

Copy context.Context without setting timeout

Set up

$ go get -u github.com/knwoop/dcontext

Example

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

About

Copy context.Context without setting timeout in one

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages