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