import ( "net/http" "golang.org/x/net/context" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10) defer cancel() req, err = http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil) if err != nil { // handle error } client := http.Client{} resp, err := client.Do(req) if err != nil { // handle error } // process response }
func longRunningOperation(ctx context.Context) error { for { select { case <-ctx.Done(): return ctx.Err() default: // do some work } } } func main() { ctx, cancel := context.WithCancel(context.Background()) go func() { time.Sleep(time.Second * 10) // simulate long running operation cancel() }() if err := longRunningOperation(ctx); err != nil { // handle error or canceled context } }In this example, we use context to cancel a long running operation after 10 seconds. We pass the context to the operation and monitor the channel returned by "Done". If the channel is closed, we return the error provided by the context.