blob: cabcccd79f39f34ac3cb3ead6e563d4e769415bd [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 Wilsonb8b16f82014-10-20 10:19:49 -040039 return PageResult{
40 Result: gophercloud.Result{
Ash Wilson72e4d2c2014-10-20 10:27:30 -040041 Body: parsedBody,
42 Header: resp.Header,
Ash Wilsonb8b16f82014-10-20 10:19:49 -040043 },
44 URL: *resp.Request.URL,
Ash Wilsonc8e68872014-09-16 10:36:56 -040045 }, err
46}
47
Ash Wilsone58e5c32015-02-12 14:34:39 -050048// Request performs an HTTP request and extracts the http.Response from the result.
49func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) {
50 return client.Request("GET", url, gophercloud.RequestOpts{
51 MoreHeaders: headers,
Ash Wilsonc8e68872014-09-16 10:36:56 -040052 OkCodes: []int{200, 204},
53 })
Ash Wilsonc8e68872014-09-16 10:36:56 -040054}