-
Notifications
You must be signed in to change notification settings - Fork 302
/
links.go
123 lines (104 loc) · 2.49 KB
/
links.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package godo
import (
"context"
"net/url"
"strconv"
)
// Links manages links that are returned along with a List
type Links struct {
Pages *Pages `json:"pages,omitempty"`
Actions []LinkAction `json:"actions,omitempty"`
}
// Pages are pages specified in Links
type Pages struct {
First string `json:"first,omitempty"`
Prev string `json:"prev,omitempty"`
Last string `json:"last,omitempty"`
Next string `json:"next,omitempty"`
}
// LinkAction is a pointer to an action
type LinkAction struct {
ID int `json:"id,omitempty"`
Rel string `json:"rel,omitempty"`
HREF string `json:"href,omitempty"`
}
// CurrentPage is current page of the list
func (l *Links) CurrentPage() (int, error) {
return l.Pages.current()
}
// NextPageToken is the page token to request the next page of the list
func (l *Links) NextPageToken() (string, error) {
return l.Pages.nextPageToken()
}
// PrevPageToken is the page token to request the previous page of the list
func (l *Links) PrevPageToken() (string, error) {
return l.Pages.prevPageToken()
}
func (p *Pages) current() (int, error) {
switch {
case p == nil:
return 1, nil
case p.Prev == "" && p.Next != "":
return 1, nil
case p.Prev != "":
prevPage, err := pageForURL(p.Prev)
if err != nil {
return 0, err
}
return prevPage + 1, nil
}
return 0, nil
}
func (p *Pages) nextPageToken() (string, error) {
if p == nil || p.Next == "" {
return "", nil
}
token, err := pageTokenFromURL(p.Next)
if err != nil {
return "", err
}
return token, nil
}
func (p *Pages) prevPageToken() (string, error) {
if p == nil || p.Prev == "" {
return "", nil
}
token, err := pageTokenFromURL(p.Prev)
if err != nil {
return "", err
}
return token, nil
}
// IsLastPage returns true if the current page is the last
func (l *Links) IsLastPage() bool {
if l.Pages == nil {
return true
}
return l.Pages.isLast()
}
func (p *Pages) isLast() bool {
return p.Next == ""
}
func pageForURL(urlText string) (int, error) {
u, err := url.ParseRequestURI(urlText)
if err != nil {
return 0, err
}
pageStr := u.Query().Get("page")
page, err := strconv.Atoi(pageStr)
if err != nil {
return 0, err
}
return page, nil
}
func pageTokenFromURL(urlText string) (string, error) {
u, err := url.ParseRequestURI(urlText)
if err != nil {
return "", err
}
return u.Query().Get("page_token"), nil
}
// Get a link action by id.
func (la *LinkAction) Get(ctx context.Context, client *Client) (*Action, *Response, error) {
return client.Actions.Get(ctx, la.ID)
}