-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent.go
52 lines (44 loc) · 1.02 KB
/
concurrent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package crawler
import (
"context"
"fmt"
"net/url"
)
type crawler interface {
Crawl(context.Context, *url.URL) ([]byte, error)
}
// ConcurrentCrawler limits number of concurrent requests.
type ConcurrentCrawler struct {
crawler crawler
sem chan struct{}
}
// WithConcurrencyLimit adds concurrency limit to the crawler.
func WithConcurrencyLimit(crawler crawler, limit int) *ConcurrentCrawler {
return &ConcurrentCrawler{
crawler: crawler,
sem: make(chan struct{}, limit),
}
}
// Crawl downloads a page.
func (c *ConcurrentCrawler) Crawl(ctx context.Context, u *url.URL) ([]byte, error) {
results := make(chan []byte)
errors := make(chan error)
go func(ctx context.Context, u *url.URL) {
c.sem <- struct{}{}
defer func() { <-c.sem }()
res, err := c.crawler.Crawl(ctx, u)
if err != nil {
errors <- err
} else {
results <- res
}
}(ctx, u)
select {
case <-ctx.Done():
return nil, fmt.Errorf("ctx cancelled")
case err := <-errors:
return nil, err
case res := <-results:
return res, nil
}
}