github.com/gophercloud/gophercloud@v1.11.0/pagination/http.go (about) 1 package pagination 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "net/http" 7 "net/url" 8 "strings" 9 10 "github.com/gophercloud/gophercloud" 11 ) 12 13 // PageResult stores the HTTP response that returned the current page of results. 14 type PageResult struct { 15 gophercloud.Result 16 url.URL 17 } 18 19 // PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the 20 // results, interpreting it as JSON if the content type indicates. 21 func PageResultFrom(resp *http.Response) (PageResult, error) { 22 var parsedBody interface{} 23 24 defer resp.Body.Close() 25 rawBody, err := ioutil.ReadAll(resp.Body) 26 if err != nil { 27 return PageResult{}, err 28 } 29 30 if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { 31 err = json.Unmarshal(rawBody, &parsedBody) 32 if err != nil { 33 return PageResult{}, err 34 } 35 } else { 36 parsedBody = rawBody 37 } 38 39 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). 44 func PageResultFromParsed(resp *http.Response, body interface{}) PageResult { 45 return PageResult{ 46 Result: gophercloud.Result{ 47 Body: body, 48 StatusCode: resp.StatusCode, 49 Header: resp.Header, 50 }, 51 URL: *resp.Request.URL, 52 } 53 } 54 55 // Request performs an HTTP request and extracts the http.Response from the result. 56 func Request(client *gophercloud.ServiceClient, headers map[string]string, url string) (*http.Response, error) { 57 return client.Get(url, nil, &gophercloud.RequestOpts{ 58 MoreHeaders: headers, 59 OkCodes: []int{200, 204, 300}, 60 KeepResponseBody: true, 61 }) 62 }