Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 1 | package pagination |
| 2 | |
Ash Wilson | 7049af4 | 2014-09-16 13:04:48 -0400 | [diff] [blame] | 3 | import "github.com/mitchellh/mapstructure" |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 4 | |
| 5 | // LinkedPageBase may be embedded to implement a page that provides navigational "Next" and "Previous" links within its result. |
| 6 | type LinkedPageBase LastHTTPResponse |
| 7 | |
| 8 | // NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present. |
| 9 | // It assumes that the links are available in a "links" element of the top-level response object. |
| 10 | // If this is not the case, override NextPageURL on your result type. |
| 11 | func (current LinkedPageBase) NextPageURL() (string, error) { |
| 12 | type response struct { |
| 13 | Links struct { |
| 14 | Next *string `mapstructure:"next,omitempty"` |
| 15 | } `mapstructure:"links"` |
| 16 | } |
| 17 | |
| 18 | var r response |
| 19 | err := mapstructure.Decode(current.Body, &r) |
| 20 | if err != nil { |
| 21 | return "", err |
| 22 | } |
| 23 | |
| 24 | if r.Links.Next == nil { |
| 25 | return "", nil |
| 26 | } |
| 27 | |
| 28 | return *r.Links.Next, nil |
| 29 | } |