github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/gotham-context/first.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 "math/rand" 8 "time" 9 ) 10 11 // START1 OMIT 12 // Search runs query on a backend and returns the result. 13 type Search func(query string) Result 14 type Result struct { 15 Hit string 16 Err error 17 } 18 19 // First runs query on replicas and returns the first result. 20 func First(query string, replicas ...Search) Result { 21 c := make(chan Result, len(replicas)) 22 search := func(replica Search) { c <- replica(query) } 23 for _, replica := range replicas { 24 go search(replica) 25 } 26 return <-c 27 } 28 29 // STOP1 OMIT 30 31 // START2 OMIT 32 func main() { 33 rand.Seed(time.Now().UnixNano()) 34 start := time.Now() 35 result := First("golang", 36 fakeSearch("replica 1"), 37 fakeSearch("replica 2")) 38 elapsed := time.Since(start) 39 fmt.Printf("%+v\n", result) 40 fmt.Println(elapsed) 41 } 42 43 // STOP2 OMIT 44 45 func fakeSearch(kind string) Search { 46 return func(query string) Result { 47 time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) 48 return Result{Hit: fmt.Sprintf("%s result for %q\n", kind, query)} 49 } 50 }