-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi_request.go
99 lines (83 loc) · 2.06 KB
/
api_request.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"encoding/json"
"io"
"io/ioutil"
"net/url"
"github.com/bndr/gopencils"
"github.com/reconquest/karma-go"
)
func request(
method string, resource *gopencils.Resource, options ...interface{},
) (interface{}, error) {
uri := resource.Url
if len(options) > 0 {
if query, ok := options[len(options)-1].(map[string]string); ok {
queryValues := url.Values{}
for key, value := range query {
queryValues.Set(key, value)
}
uri += "?" + queryValues.Encode()
}
}
var (
request *gopencils.Resource
err error
)
// oh... gopencils doesn't have exported method Do()
switch method {
case "GET":
request, err = resource.Get(options...)
case "HEAD":
request, err = resource.Head(options...)
case "POST":
request, err = resource.Post(options...)
case "PUT":
request, err = resource.Put(options...)
case "DELETE":
request, err = resource.Delete(options...)
default:
panic("unexpected method")
}
if err == nil || err == io.EOF {
err = extractRequestError(request, err)
}
if err != nil {
return nil, karma.Format(err, "can't request %s %s", method, uri)
}
return request.Response, nil
}
func extractRequestError(request *gopencils.Resource, err error) error {
if request.Raw.StatusCode < 400 {
return nil
}
unexpectedStatusCode := "remote server responds with unexpected status " +
"(" + request.Raw.Status + ")"
responseBody, err := ioutil.ReadAll(request.Raw.Body)
if err != nil {
return karma.Format(
karma.Format(err, "can't read response body"),
unexpectedStatusCode,
)
}
var responseError ResponseError
err = json.Unmarshal(responseBody, &responseError)
if len(responseError.Errors) > 0 {
return karma.Format(
responseError.String(),
unexpectedStatusCode,
)
}
if err != nil {
return karma.Format(
karma.Format(
string(responseBody),
"can't decode JSON",
),
unexpectedStatusCode,
)
}
// response is JSON, but not ResponseError (or empty message with
// Java exception), should return as is
return karma.Format(string(responseBody), unexpectedStatusCode)
}