github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/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/huaweicloud/golangsdk" 11 ) 12 13 // PageResult stores the HTTP response that returned the current page of results. 14 type PageResult struct { 15 golangsdk.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: golangsdk.Result{ 47 Body: body, 48 Header: resp.Header, 49 }, 50 URL: *resp.Request.URL, 51 } 52 } 53 54 // Request performs an HTTP request and extracts the http.Response from the result. 55 func Request(client *golangsdk.ServiceClient, headers map[string]string, url string) (*http.Response, error) { 56 return client.Get(url, nil, &golangsdk.RequestOpts{ 57 MoreHeaders: headers, 58 OkCodes: []int{200, 204, 300}, 59 KeepResponseBody: true, 60 }) 61 }