ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() req, err := http.NewRequest("GET", "http://example.com", nil) if err != nil { // handle error } // make the request with the new context resp, err := http.DefaultClient.Do(req.WithContext(ctx)) if err != nil { // handle error } defer resp.Body.Close()
func doSomething(ctx context.Context) error { // do some work // check for cancellation select { case <-ctx.Done(): return ctx.Err() default: } // do more work return nil } func doSomethingElse(ctx context.Context) error { // do some work err := doSomething(ctx) if err != nil { return err } // do more work return nil } func main() { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() // start doSomethingElse in a goroutine go func() { err := doSomethingElse(ctx) if err != nil { // handle error } }() // cancel the operation after 5 seconds time.AfterFunc(5*time.Second, cancel) // wait for the operation to complete time.Sleep(10 * time.Second) }In this example, we create a new context with a cancellation function, and use it to call `doSomethingElse` in a goroutine. We then set a timer to cancel the context after 5 seconds. In each function, we check for cancellation by calling the `Done` method of the context, and returning an error if the context has been cancelled. Overall, the Context package from github.com/coreos/flannel/godeps/_workspace/src/golang.org/x/net/context is a powerful tool for managing the lifetime of operations in Go. It allows you to set timeouts, propagate cancellation signals, and more, making it a useful library for any Go programmer.