-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaginator.go
More file actions
74 lines (64 loc) · 1.34 KB
/
paginator.go
File metadata and controls
74 lines (64 loc) · 1.34 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
70
71
72
73
74
//
// paginator.go
// Copyright (C) 2017 weirdgiraffe <giraffe@cyberzoo.xyz>
//
// Distributed under terms of the MIT license.
//
package github
import (
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
const defaultPerPage = 100
type Paginator struct {
PerPage int
req *http.Request
client *Client
next, last string
}
func NewPaginator(c *Client, req *http.Request) *Paginator {
return &Paginator{
PerPage: defaultPerPage,
req: req,
client: c,
}
}
func (p *Paginator) Next() (res *http.Response, err error) {
if p.req.URL.String() == p.last && p.last != "" {
return nil, io.EOF
}
if p.next != "" {
p.req.URL, err = url.Parse(p.next)
if err != nil {
return
}
}
q := p.req.URL.Query()
q.Set("per_page", strconv.Itoa(p.PerPage))
p.req.URL.RawQuery = q.Encode()
res, err = p.client.Do(p.req)
if err != nil {
return nil, err
}
p.update(res)
return res, nil
}
func (p *Paginator) update(res *http.Response) {
link := strings.Split(res.Header.Get("Link"), ",")
for i := range link {
part := strings.Split(link[i], ";")
if len(part) == 2 {
if strings.TrimSpace(part[1]) == `rel="next"` {
raw := strings.TrimSpace(part[0])
p.next = raw[1 : len(raw)-1]
}
if strings.TrimSpace(part[1]) == `rel="last"` {
raw := strings.TrimSpace(part[0])
p.last = raw[1 : len(raw)-1]
}
}
}
}