ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) defer cancel() select { case <-time.After(10 * time.Second): fmt.Println("I slept for 10 seconds") case <-ctx.Done(): fmt.Println(ctx.Err()) // prints "context deadline exceeded" }
type MyContextKeyType int const MyContextKey MyContextKeyType = 0 func DoSomething(ctx context.Context) { value := ctx.Value(MyContextKey) fmt.Println("The value found in the context is:", value) } func main() { ctx := context.WithValue(context.Background(), MyContextKey, "hello world") DoSomething(ctx) // The value found in the context is: hello world }Overall, the go github.com.coreos.etcd.godeps._workspace.src.golang.org.x.net.context package provides powerful tools for managing the lifecycle of your goroutines and implementing timeouts and cancellations in your program.