golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/context/withtimeout_test.go (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package context_test
     6  
     7  import (
     8  	"fmt"
     9  	"time"
    10  
    11  	"golang.org/x/net/context"
    12  )
    13  
    14  // This example passes a context with a timeout to tell a blocking function that
    15  // it should abandon its work after the timeout elapses.
    16  func ExampleWithTimeout() {
    17  	// Pass a context with a timeout to tell a blocking function that it
    18  	// should abandon its work after the timeout elapses.
    19  	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    20  	defer cancel()
    21  
    22  	select {
    23  	case <-time.After(1 * time.Second):
    24  		fmt.Println("overslept")
    25  	case <-ctx.Done():
    26  		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
    27  	}
    28  
    29  	// Output:
    30  	// context deadline exceeded
    31  }