Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 1 | package pagination |
| 2 | |
| 3 | import "github.com/rackspace/gophercloud" |
| 4 | |
| 5 | // MarkerPage is a stricter Page interface that describes additional functionality required for use with NewMarkerPager. |
| 6 | // For convenience, embed the MarkedPageBase struct. |
| 7 | type MarkerPage interface { |
| 8 | Page |
| 9 | |
Ash Wilson | 7486351 | 2014-09-16 11:45:51 -0400 | [diff] [blame^] | 10 | // LastMarker returns the last "marker" value on this page. |
| 11 | LastMarker() (string, error) |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 12 | } |
| 13 | |
| 14 | // MarkerPageBase is a page in a collection that's paginated by "limit" and "marker" query parameters. |
| 15 | type MarkerPageBase struct { |
| 16 | LastHTTPResponse |
| 17 | |
| 18 | // A reference to the embedding struct. |
| 19 | Self MarkerPage |
| 20 | } |
| 21 | |
| 22 | // NextPageURL generates the URL for the page of results after this one. |
| 23 | func (current MarkerPageBase) NextPageURL() (string, error) { |
| 24 | currentURL := current.URL |
| 25 | |
Ash Wilson | 7486351 | 2014-09-16 11:45:51 -0400 | [diff] [blame^] | 26 | mark, err := current.Self.LastMarker() |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 27 | if err != nil { |
| 28 | return "", err |
| 29 | } |
| 30 | |
| 31 | q := currentURL.Query() |
| 32 | q.Set("marker", mark) |
| 33 | currentURL.RawQuery = q.Encode() |
| 34 | |
| 35 | return currentURL.String(), nil |
| 36 | } |
| 37 | |
| 38 | // NewMarkerPager creates a Pager that iterates over successive pages by issuing requests with a "marker" parameter set to the |
| 39 | // final element of the previous Page. |
| 40 | func NewMarkerPager(client *gophercloud.ServiceClient, initialURL string, createPage func(resp LastHTTPResponse) MarkerPage) Pager { |
| 41 | |
| 42 | fetchNextPage := func(currentURL string) (Page, error) { |
| 43 | resp, err := Request(client, currentURL) |
| 44 | if err != nil { |
| 45 | return nullPage{}, err |
| 46 | } |
| 47 | |
| 48 | last, err := RememberHTTPResponse(resp) |
| 49 | if err != nil { |
| 50 | return nullPage{}, err |
| 51 | } |
| 52 | |
| 53 | return createPage(last), nil |
| 54 | } |
| 55 | |
| 56 | return Pager{ |
| 57 | initialURL: initialURL, |
| 58 | fetchNextPage: fetchNextPage, |
| 59 | } |
| 60 | } |