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