-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
47 lines (40 loc) · 1.08 KB
/
Copy pathhandler.go
File metadata and controls
47 lines (40 loc) · 1.08 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
package goscrape
import (
"net/url"
"regexp"
"strings"
)
const (
HighPriority uint = 31
MediumPriority uint = 15
LowPriority uint = 0
)
type Handler func(WebScraper, *url.URL)
type patternHandlerPair struct {
pattern *regexp.Regexp
handler Handler
priority uint
}
type PatternHandler struct {
handlers []patternHandlerPair
}
// Register associates a handler with the given pattern. Handlers are given
// the opportunity to handle URLs in the order they were registered.
func (s *PatternHandler) Register(pattern *regexp.Regexp, handler Handler, priority uint) {
s.handlers = append(s.handlers, patternHandlerPair{
pattern: pattern,
handler: handler,
priority: priority,
})
}
// Handle tries to pass the page off to the first registered handler that
// matches, returning true only if a handler exists.
func (h *PatternHandler) GetHandler(page *url.URL) (Handler, uint, bool) {
for _, ph := range h.handlers {
lowerPage := strings.ToLower(page.String())
if ph.pattern.MatchString(lowerPage) {
return ph.handler, ph.priority, true
}
}
return nil, 0, false
}