github.com/opentelekomcloud/gophertelekomcloud@v0.9.3/pagination/http.go (about) 1 package pagination 2 3 import ( 4 "bytes" 5 "io" 6 "net/http" 7 "net/url" 8 9 "github.com/opentelekomcloud/gophertelekomcloud" 10 "github.com/opentelekomcloud/gophertelekomcloud/internal/extract" 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 func (r PageResult) GetBody() []byte { 20 return r.Body 21 } 22 23 // GetBodyAsSlice tries to convert page body to a slice, returning nil on fail 24 func (r PageResult) GetBodyAsSlice() ([]any, error) { 25 result := make([]any, 0) 26 27 if err := extract.Into(bytes.NewReader(r.Body), &result); err != nil { 28 return nil, err 29 } 30 31 return result, nil 32 } 33 34 // GetBodyAsMap tries to convert page body to a map, returning nil on fail 35 func (r PageResult) GetBodyAsMap() (map[string]any, error) { 36 result := make(map[string]any, 0) 37 38 if err := extract.Into(bytes.NewReader(r.Body), &result); err != nil { 39 return nil, err 40 } 41 42 return result, nil 43 } 44 45 // PageResultFrom parses an HTTP response as JSON and returns a PageResult containing the 46 // results, interpreting it as JSON if the content type indicates. 47 func PageResultFrom(resp *http.Response) (PageResult, error) { 48 defer resp.Body.Close() 49 rawBody, err := io.ReadAll(resp.Body) 50 if err != nil { 51 return PageResult{}, err 52 } 53 54 return PageResult{ 55 Result: golangsdk.Result{ 56 Body: rawBody, 57 Header: resp.Header, 58 }, 59 URL: *resp.Request.URL, 60 }, nil 61 } 62 63 // Request performs an HTTP request and extracts the http.Response from the result. 64 func Request(client *golangsdk.ServiceClient, headers map[string]string, url string) (*http.Response, error) { 65 return client.Get(url, nil, &golangsdk.RequestOpts{ 66 MoreHeaders: headers, 67 OkCodes: []int{200, 204, 300}, 68 }) 69 } 70 71 // NewPageResult stores the HTTP response that returned the current page of results. 72 type NewPageResult struct { 73 // Body is the payload of the HTTP response from the server. 74 Body []byte 75 76 // Header contains the HTTP header structure from the original response. 77 Header http.Header 78 79 URL url.URL 80 } 81 82 func (r NewPageResult) NewGetBody() []byte { 83 return r.Body 84 } 85 86 // NewGetBodyAsMap tries to convert page body to a map, returning nil on fail 87 func (r NewPageResult) NewGetBodyAsMap() (map[string]any, error) { 88 result := make(map[string]any, 0) 89 90 if err := extract.Into(bytes.NewReader(r.Body), &result); err != nil { 91 return nil, err 92 } 93 94 return result, nil 95 } 96 97 // NewGetBodyAsSlice tries to convert page body to a slice, returning nil on fail 98 func (r NewPageResult) NewGetBodyAsSlice() ([]any, error) { 99 result := make([]any, 0) 100 101 if err := extract.Into(bytes.NewReader(r.Body), &result); err != nil { 102 return nil, err 103 } 104 105 return result, nil 106 }