github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2015/go-for-java-programmers/google-timeout.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"math/rand"
     8  	"time"
     9  )
    10  
    11  type Result string
    12  type Search func(query string) Result
    13  
    14  var (
    15  	Web   = fakeSearch("web")
    16  	Image = fakeSearch("image")
    17  	Video = fakeSearch("video")
    18  )
    19  
    20  func Google(query string) (results []Result) {
    21  	// START OMIT
    22  	c := make(chan Result, 3)
    23  	go func() { c <- Web(query) }()
    24  	go func() { c <- Image(query) }()
    25  	go func() { c <- Video(query) }()
    26  
    27  	timeout := time.After(80 * time.Millisecond)
    28  	for i := 0; i < 3; i++ {
    29  		select { // HL
    30  		case result := <-c: // HL
    31  			results = append(results, result)
    32  		case <-timeout: // HL
    33  			fmt.Println("timed out")
    34  			return
    35  		}
    36  	}
    37  	return
    38  	// STOP OMIT
    39  }
    40  
    41  func fakeSearch(kind string) Search {
    42  	return func(query string) Result {
    43  		time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
    44  		return Result(fmt.Sprintf("%s result for %q\n", kind, query))
    45  	}
    46  }
    47  
    48  func init() {
    49  	rand.Seed(time.Now().UnixNano())
    50  }
    51  
    52  func main() {
    53  	start := time.Now()
    54  	results := Google("golang")
    55  	elapsed := time.Since(start)
    56  	fmt.Println(results)
    57  	fmt.Println(elapsed)
    58  }