Last active
January 12, 2019 08:52
-
-
Save rakeshopensource/6f3f59554953162bdcf8e40dd1ed52fa to your computer and use it in GitHub Desktop.
Fake google search example in Go using concurrent Go routines.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
var ( | |
Web = fakeSearch("web") | |
Web1 = fakeSearch("web1") | |
Image = fakeSearch("image") | |
Image1 = fakeSearch("image1") | |
Video = fakeSearch("video") | |
Video1 = fakeSearch("video1") | |
) | |
type Result string | |
type Results []Result | |
type Search func(query string) Result | |
func fakeSearch(kind string) Search { | |
return func(query string) Result { | |
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) | |
return Result(fmt.Sprintf("%s result for %q\n", kind, query)) | |
} | |
} | |
func SearchReplica(query string, replicas ...Search) Result { | |
c := make(chan Result) | |
searchReplica := func(i int) { | |
c <- replicas[i](query) | |
} | |
for i := range replicas { | |
go searchReplica(i) | |
} | |
return <-c | |
} | |
func Google(query string) (results Results) { | |
c := make(chan Result) | |
go func() { | |
c <- SearchReplica(query, Web, Web1) | |
}() | |
go func() { | |
c <- SearchReplica(query, Image, Image1) | |
}() | |
go func() { | |
c <- SearchReplica(query, Video, Video1) | |
}() | |
timeout := time.After(80 * time.Millisecond) | |
for i := 0; i < 3; i++ { | |
select { | |
case result := <-c: | |
results = append(results, result) | |
case <-timeout: | |
fmt.Println("Timeout !!!") | |
return | |
} | |
} | |
return | |
} | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
start := time.Now() | |
results := Google("golang") | |
elapsed := time.Since(start) | |
fmt.Println(results) | |
fmt.Println(elapsed) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment