An unbuffered channel has no storage capacity. A send and receive must meet before the value can pass, so it coordinates goroutines as well as carrying data. Create one with make(chan T), without a capacity argument. section 9.4
Hand articles to a saver
Create out := make(chan *gofeed.Article), start a saving goroutine, then send each fetched article with out <- article. The saver receives with for article := range out. Close out after sending so the loop can finish. section 9.4
Listing 9.16 main.go: Passing a channel to another function
func fetchFeed(ctx context.Context, url string) (gofeed.Feed, error) {
fmt.Println("fetching feed: ", url)
fp := gofeed.NewParser()
feed, err := fp.ParseURLWithContext(ctx, url)
if err != nil {
return gofeed.Feed{}, err
}
fmt.Println("fetched: ", url)
out := make(chan *gofeed.Article) #1
go saveFeed(out) #2
defer close(out) #3
for _, article := range feed.Article{
fmt.Println("ingesting article: ", article.Link)
out <- article #4
}
fmt.Println("processed: ", url)
return feed, nil
}
The fetch-and-save listing shows channel creation, a receiving goroutine, sends, and deferred closure together. section 9.4
