-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
69 lines (63 loc) · 1.79 KB
/
Copy pathmain.go
File metadata and controls
69 lines (63 loc) · 1.79 KB
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
61
62
63
64
65
66
67
68
69
package main
import (
"context"
"log"
"net/url"
"sync"
"sync/atomic"
)
type URLLoggingWithLinksPostProcessor struct {
URLsCrawled sync.Map
PagesProcessed atomic.Int64
LinksFound atomic.Int64
}
func (s *URLLoggingWithLinksPostProcessor) Process(ctx context.Context, pageURL *url.URL, pageContent string) error {
log.Printf("URLLoggingWithLinksPostProcessor processing page: %s", pageURL.String())
urls, err := ExtractLinks(pageContent)
if err != nil {
return err
}
s.URLsCrawled.Store(pageURL.String(), urls)
s.PagesProcessed.Add(1)
s.LinksFound.Add(int64(len(urls)))
return nil
}
func main() {
baseUrl, _ := url.Parse("https://bbc.co.uk/")
processor := &URLLoggingWithLinksPostProcessor{}
logger := StdoutLogger{}
ctx, cancel := context.WithCancel(context.Background())
crawler, err := NewSiteCrawler(
ctx,
*baseUrl,
&logger,
5000,
"Mozilla/5.0 (compatible; JakeBot/1.0; +https://jakesaunders.dev/bot)",
2,
[]PostProcessor{processor},
)
if err != nil {
logger.Error("Failed to create site crawler: %v", err)
return
}
err = crawler.Crawl(ctx)
if err != nil {
logger.Error("Failed to crawl site: %v", err)
} else {
logger.Info("Crawl completed successfully")
}
// print crawled urls as per specification
logger.Info("-------------------- BEGIN SPECIFICATION OUTPUT --------------------")
processor.URLsCrawled.Range(func(key, value interface{}) bool {
logger.Info("Crawled URL: %s and found links:", key.(string))
for _, link := range value.([]string) {
logger.Info(" - %s", link)
}
return true
})
// print summary
logger.Info("Total pages processed: %d", processor.PagesProcessed.Load())
logger.Info("Total links found: %d", processor.LinksFound.Load())
logger.Info("-------------------- END SPECIFICATION OUTPUT --------------------")
cancel()
}