-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaginator.go
More file actions
54 lines (49 loc) · 1.58 KB
/
paginator.go
File metadata and controls
54 lines (49 loc) · 1.58 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
package listeater
import (
"errors"
"github.com/PuerkitoBio/goquery"
"log"
"net/http"
//"net/url"
)
var ErrInvalidSelector = errors.New("Invalid selector for pagination.")
var ErrNoHrefInPagination = errors.New("Pagination found but no href inside.")
var ErrInvalidUrlHrefInPagination = errors.New("Pagination found but url in href not found.")
//the interface that must be implemented to paginate from a page.
//Returns request for next page, hasNext bool, and an error
type PaginationHandler interface {
Paginate(r *http.Response) (*http.Request, bool, error)
}
//a simple pagination handler that extracts the href from the specified element
type HrefPaginationHandler struct {
Selector string `json:"selector"`
}
func (hph HrefPaginationHandler) Paginate(r *http.Response) (*http.Request, bool, error) {
if hph.Selector == "" {
return nil, false, ErrInvalidSelector
}
//extract the pagination link
p, err := goquery.NewDocumentFromResponse(r)
if err != nil {
return nil, false, err
}
np := p.Find(hph.Selector).First()
if np == nil || len(np.Nodes) < 1 {
log.Println("no more pages") //this is good exit
return nil, false, nil
}
nextUrl, exist := np.Attr("href")
if !exist {
log.Println("WARNING: no href matched pagination selelector")
return nil, false, ErrNoHrefInPagination
}
//extract a valid url
nextUrl = urlRegex.FindString(nextUrl)
if nextUrl == "" {
log.Println("WARNING: no valid url found in href")
return nil, false, ErrInvalidUrlHrefInPagination
}
log.Println("Next page: " + nextUrl)
req, _ := http.NewRequest("GET", nextUrl, nil)
return req, true, nil
}