

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Concurrency
incomplete
2: Max Pages
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Why write a web crawler with Go and not use concurrency? Let's speed this bad boy up with some goroutines!
To coordinate the goroutines, we'll use:
pages map.main from exiting until all requests finish.type config struct {
pages map[string]PageData
baseURL *url.URL
mu *sync.Mutex
concurrencyControl chan struct{}
wg *sync.WaitGroup
}
func (cfg *config) crawlPage(rawCurrentURL string)
extractPageData for each successfully fetched page, using the current page's URL, and crawl its OutgoingLinks.pages map safe with the mutex.When you're satisfied with the results, you can move on.
I created this method to call as a helper inside of crawlPage:
func (cfg *config) addPageVisit(normalizedURL string) (shouldVisit bool)
addPageVisit method returns a boolean: to indicate whether we should crawl the page.<-cfg.concurrencyControl) channel. This ensures that the wg is decremented and the channel is emptied even when the goroutine errors and returns early.main function.