Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 1 | package pagination |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "io/ioutil" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | |
| 9 | "github.com/racker/perigee" |
| 10 | "github.com/rackspace/gophercloud" |
| 11 | ) |
| 12 | |
| 13 | // LastHTTPResponse stores generic information derived from an HTTP response. |
| 14 | type LastHTTPResponse struct { |
| 15 | url.URL |
| 16 | http.Header |
| 17 | Body interface{} |
| 18 | } |
| 19 | |
| 20 | // RememberHTTPResponse parses an HTTP response as JSON and returns a LastHTTPResponse containing the results. |
| 21 | // The main reason to do this instead of holding the response directly is that a response body can only be read once. |
| 22 | // Also, this centralizes the JSON decoding. |
| 23 | func RememberHTTPResponse(resp http.Response) (LastHTTPResponse, error) { |
| 24 | var parsedBody interface{} |
| 25 | |
| 26 | defer resp.Body.Close() |
| 27 | rawBody, err := ioutil.ReadAll(resp.Body) |
| 28 | if err != nil { |
| 29 | return LastHTTPResponse{}, err |
| 30 | } |
| 31 | |
| 32 | if resp.Header.Get("Content-Type") == "application/json" { |
| 33 | err = json.Unmarshal(rawBody, &parsedBody) |
| 34 | if err != nil { |
| 35 | return LastHTTPResponse{}, err |
| 36 | } |
| 37 | } else { |
| 38 | parsedBody = rawBody |
| 39 | } |
| 40 | |
| 41 | return LastHTTPResponse{ |
| 42 | URL: *resp.Request.URL, |
| 43 | Header: resp.Header, |
| 44 | Body: parsedBody, |
| 45 | }, err |
| 46 | } |
| 47 | |
| 48 | // Request performs a Perigee request and extracts the http.Response from the result. |
| 49 | func Request(client *gophercloud.ServiceClient, url string) (http.Response, error) { |
| 50 | resp, err := perigee.Request("GET", url, perigee.Options{ |
| 51 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 52 | OkCodes: []int{200, 204}, |
| 53 | }) |
| 54 | if err != nil { |
| 55 | return http.Response{}, err |
| 56 | } |
| 57 | return resp.HttpResponse, nil |
| 58 | } |