Skip to content

Commit 57aac36

Browse files
Refactor based on Erik's suggestions
1 parent 6a9d73b commit 57aac36

2 files changed

Lines changed: 24 additions & 16 deletions

File tree

‎src/chapter2/search/find/find.go‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package find
22

33
import (
44
"log"
5+
"sync"
56

67
"github.com/goinaction/code/src/chapter2/search/feeds"
78
)
@@ -29,13 +30,10 @@ type (
2930
)
3031

3132
// Search pulls down each feed looking for the search term.
32-
func Search(matcher Matcher, searchTerm string, site feeds.Site, captureResults chan []Result) {
33-
// Make sure each find returns a result.
34-
var err error
33+
func Search(matcher Matcher, searchTerm string, site feeds.Site, result chan Result, waitGroup *sync.WaitGroup) {
34+
// Call done so we can report we are finished processing.
3535
defer func() {
36-
if err != nil {
37-
captureResults <- nil
38-
}
36+
waitGroup.Done()
3937
}()
4038

4139
log.Printf("Search Feed Type[%s] Site[%s] For Uri[%s]\n", site.Type, site.Name, site.Uri)
@@ -55,5 +53,7 @@ func Search(matcher Matcher, searchTerm string, site feeds.Site, captureResults
5553
}
5654

5755
// Write the results to the channel.
58-
captureResults <- searchResults
56+
for _, searchResult := range searchResults {
57+
result <- searchResult
58+
}
5959
}

‎src/chapter2/search/main.go‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"log"
5+
"sync"
56

67
"github.com/goinaction/code/src/chapter2/search/feeds"
78
"github.com/goinaction/code/src/chapter2/search/find"
@@ -21,7 +22,19 @@ func main() {
2122

2223
// Perpare the slice of results and the channel to
2324
// retrieve the results on.
24-
results := make(chan []find.Result)
25+
result := make(chan find.Result)
26+
27+
// Wait for the result from each goroutine
28+
go func() {
29+
for site := 0; site < len(sites); site++ {
30+
found := <-result
31+
log.Printf("%s:\n%s\n\n", found.Field, found.Content)
32+
}
33+
}()
34+
35+
// Setup a wait group so we can process all the feeds.
36+
var waitGroup sync.WaitGroup
37+
waitGroup.Add(len(sites))
2538

2639
// Launch a goroutine for each feed to find the results.
2740
for _, site := range sites {
@@ -37,14 +50,9 @@ func main() {
3750
}
3851

3952
// Launch the goroutine to perform the search.
40-
go find.Search(matcher, searchTerm, site, results)
53+
go find.Search(matcher, searchTerm, site, result, &waitGroup)
4154
}
4255

43-
// Wait for the result from each goroutine
44-
for site := 0; site < len(sites); site++ {
45-
found := <-results
46-
for _, result := range found {
47-
log.Printf("%s:\n%s\n\n", result.Field, result.Content)
48-
}
49-
}
56+
// Wait for everything to be processed.
57+
waitGroup.Wait()
5058
}

0 commit comments

Comments
 (0)