blob: 1e108c8039151e309fb18c1c952723529e3a128d [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
10 "github.com/racker/perigee"
11 "github.com/rackspace/gophercloud"
12)
13
Ash Wilsonb8b16f82014-10-20 10:19:49 -040014// PageResult stores the HTTP response that returned the current page of results.
15type PageResult struct {
16 gophercloud.Result
Ash Wilsonc8e68872014-09-16 10:36:56 -040017 url.URL
Ash Wilsonc8e68872014-09-16 10:36:56 -040018}
19
Ash Wilsonb8b16f82014-10-20 10:19:49 -040020// PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the
21// results, interpreting it as JSON if the content type indicates.
22func PageResultFrom(resp http.Response) (PageResult, error) {
Ash Wilsonc8e68872014-09-16 10:36:56 -040023 var parsedBody interface{}
24
25 defer resp.Body.Close()
26 rawBody, err := ioutil.ReadAll(resp.Body)
27 if err != nil {
Ash Wilsonb8b16f82014-10-20 10:19:49 -040028 return PageResult{}, err
Ash Wilsonc8e68872014-09-16 10:36:56 -040029 }
30
Ash Wilsona7402472014-09-16 15:18:34 -040031 if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
Ash Wilsonc8e68872014-09-16 10:36:56 -040032 err = json.Unmarshal(rawBody, &parsedBody)
33 if err != nil {
Ash Wilsonb8b16f82014-10-20 10:19:49 -040034 return PageResult{}, err
Ash Wilsonc8e68872014-09-16 10:36:56 -040035 }
36 } else {
37 parsedBody = rawBody
38 }
39
Ash Wilsonb8b16f82014-10-20 10:19:49 -040040 return PageResult{
41 Result: gophercloud.Result{
Ash Wilson72e4d2c2014-10-20 10:27:30 -040042 Body: parsedBody,
43 Header: resp.Header,
Ash Wilsonb8b16f82014-10-20 10:19:49 -040044 },
45 URL: *resp.Request.URL,
Ash Wilsonc8e68872014-09-16 10:36:56 -040046 }, err
47}
48
49// Request performs a Perigee request and extracts the http.Response from the result.
Ash Wilsona7402472014-09-16 15:18:34 -040050func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (http.Response, error) {
Ash Wilson77857dc2014-10-22 09:09:02 -040051 h := client.AuthenticatedHeaders()
Ash Wilsona7402472014-09-16 15:18:34 -040052 for key, value := range headers {
53 h[key] = value
54 }
55
Ash Wilsonc8e68872014-09-16 10:36:56 -040056 resp, err := perigee.Request("GET", url, perigee.Options{
Ash Wilsona7402472014-09-16 15:18:34 -040057 MoreHeaders: h,
Ash Wilsonc8e68872014-09-16 10:36:56 -040058 OkCodes: []int{200, 204},
59 })
60 if err != nil {
61 return http.Response{}, err
62 }
63 return resp.HttpResponse, nil
64}