forked from digitalocean/godo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
links.go
82 lines (68 loc) · 1.58 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
package godo
import (
"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()
}
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
}
// 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.Last == ""
}
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
}
// Get a link action by id.
func (la *LinkAction) Get(client *Client) (*Action, *Response, error) {
return client.Actions.Get(la.ID)
}