blob: 1b3fe94ab9f23e7b3c7795b6233720c9216bdc2c [file] [log] [blame]
Ash Wilsonc8e68872014-09-16 10:36:56 -04001package pagination
2
3import (
4 "encoding/json"
5 "io/ioutil"
6 "net/http"
7 "net/url"
Ash Wilsona7402472014-09-16 15:18:34 -04008 "strings"
Ash Wilsonc8e68872014-09-16 10:36:56 -04009
Ash Wilsonc8e68872014-09-16 10:36:56 -040010 "github.com/rackspace/gophercloud"
11)
12
Ash Wilsonb8b16f82014-10-20 10:19:49 -040013// PageResult stores the HTTP response that returned the current page of results.
14type PageResult struct {
15 gophercloud.Result
Ash Wilsonc8e68872014-09-16 10:36:56 -040016 url.URL
Ash Wilsonc8e68872014-09-16 10:36:56 -040017}
18
Ash Wilsonb8b16f82014-10-20 10:19:49 -040019// PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the
20// results, interpreting it as JSON if the content type indicates.
Ash Wilsone58e5c32015-02-12 14:34:39 -050021func PageResultFrom(resp *http.Response) (PageResult, error) {
Ash Wilsonc8e68872014-09-16 10:36:56 -040022 var parsedBody interface{}
23
24 defer resp.Body.Close()
25 rawBody, err := ioutil.ReadAll(resp.Body)
26 if err != nil {
Ash Wilsonb8b16f82014-10-20 10:19:49 -040027 return PageResult{}, err
Ash Wilsonc8e68872014-09-16 10:36:56 -040028 }
29
Ash Wilsona7402472014-09-16 15:18:34 -040030 if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
Ash Wilsonc8e68872014-09-16 10:36:56 -040031 err = json.Unmarshal(rawBody, &parsedBody)
32 if err != nil {
Ash Wilsonb8b16f82014-10-20 10:19:49 -040033 return PageResult{}, err
Ash Wilsonc8e68872014-09-16 10:36:56 -040034 }
35 } else {
36 parsedBody = rawBody
37 }
38
Ash Wilson2c749a02015-06-24 10:16:16 -040039 return PageResultFromParsed(resp, parsedBody), err
40}
41
42// PageResultFromParsed constructs a PageResult from an HTTP response that has already had its
43// body parsed as JSON (and closed).
44func PageResultFromParsed(resp *http.Response, body interface{}) PageResult {
Ash Wilsonb8b16f82014-10-20 10:19:49 -040045 return PageResult{
46 Result: gophercloud.Result{
Ash Wilson2c749a02015-06-24 10:16:16 -040047 Body: body,
Ash Wilson72e4d2c2014-10-20 10:27:30 -040048 Header: resp.Header,
Ash Wilsonb8b16f82014-10-20 10:19:49 -040049 },
50 URL: *resp.Request.URL,
Ash Wilson2c749a02015-06-24 10:16:16 -040051 }
Ash Wilsonc8e68872014-09-16 10:36:56 -040052}
53
Ash Wilsone58e5c32015-02-12 14:34:39 -050054// Request performs an HTTP request and extracts the http.Response from the result.
55func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) {
56 return client.Request("GET", url, gophercloud.RequestOpts{
57 MoreHeaders: headers,
Ash Wilsonc8e68872014-09-16 10:36:56 -040058 OkCodes: []int{200, 204},
59 })
Ash Wilsonc8e68872014-09-16 10:36:56 -040060}