-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
60 lines (48 loc) · 903 Bytes
/
main.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
53
54
55
56
57
58
59
60
package main
import (
"net/http"
"time"
"io"
"sync"
)
type Scrapper struct {
client *http.Client
}
type ScrapedHTML struct {
URL string
Content string
Error error
}
func NewScrapper() *Scrapper {
return &Scrapper{
client: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (s *Scrapper) Scrape(url string) (string, error) {
resp, err := s.client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func (s *Scrapper) ScrapeConcurrent(urls []string) []ScrapedHTML {
var wg sync.WaitGroup
results := make([]ScrapedHTML, len(urls))
for i, url := range urls {
wg.Add(1)
go func(i int, url string) {
defer wg.Done()
content, err := s.Scrape(url)
results[i] = ScrapedHTML{url, content, err}
}(i, url)
}
wg.Wait()
return results
}