forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
81 lines (72 loc) · 1.74 KB
/
json.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
package aws
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
// JSONClient is the underlying client for JSON APIs.
type JSONClient struct {
Context Context
Client *http.Client
Endpoint string
TargetPrefix string
JSONVersion string
}
// Do sends an HTTP request and returns an HTTP response, following policy
// (e.g. redirects, cookies, auth) as configured on the client.
func (c *JSONClient) Do(op, method, uri string, req, resp interface{}) error {
b, err := json.Marshal(req)
if err != nil {
return err
}
httpReq, err := http.NewRequest(method, c.Endpoint+uri, bytes.NewReader(b))
if err != nil {
return err
}
httpReq.Header.Set("User-Agent", "aws-go")
httpReq.Header.Set("X-Amz-Target", c.TargetPrefix+"."+op)
httpReq.Header.Set("Content-Type", "application/x-amz-json-"+c.JSONVersion)
if err := c.Context.sign(httpReq); err != nil {
return err
}
httpResp, err := c.Client.Do(httpReq)
if err != nil {
return err
}
defer func() {
_ = httpResp.Body.Close()
}()
if httpResp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return err
}
if len(bodyBytes) == 0 {
return APIError{
StatusCode: httpResp.StatusCode,
Message: httpResp.Status,
}
}
var jsonErr jsonErrorResponse
if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
return err
}
return jsonErr.Err(httpResp.StatusCode)
}
if resp != nil {
return json.NewDecoder(httpResp.Body).Decode(resp)
}
return nil
}
type jsonErrorResponse struct {
Type string `json:"__type"`
Message string `json:"message"`
}
func (e jsonErrorResponse) Err(StatusCode int) error {
return APIError{
StatusCode: StatusCode,
Type: e.Type,
Message: e.Message,
}
}