This repository has been archived by the owner on Mar 24, 2022. It is now read-only.
forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_request.go
96 lines (76 loc) · 2.11 KB
/
client_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
package uaa
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshhttp "github.com/cloudfoundry/bosh-utils/httpclient"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
type ClientRequest struct {
endpoint string
httpClient boshhttp.HTTPClient
logger boshlog.Logger
}
func NewClientRequest(
endpoint string,
httpClient boshhttp.HTTPClient,
logger boshlog.Logger,
) ClientRequest {
return ClientRequest{
endpoint: endpoint,
httpClient: httpClient,
logger: logger,
}
}
func (r ClientRequest) Get(path string, response interface{}) error {
url := fmt.Sprintf("%s%s", r.endpoint, path)
setHeaders := func(req *http.Request) {
req.Header.Add("Accept", "application/json")
}
resp, err := r.httpClient.GetCustomized(url, setHeaders)
if err != nil {
return bosherr.WrapErrorf(err, "Performing request GET '%s'", url)
}
respBody, err := r.readResponse(resp)
if err != nil {
return err
}
err = json.Unmarshal(respBody, &response)
if err != nil {
return bosherr.WrapError(err, "Unmarshaling UAA response")
}
return nil
}
func (r ClientRequest) Post(path string, payload []byte, response interface{}) error {
url := fmt.Sprintf("%s%s", r.endpoint, path)
setHeaders := func(req *http.Request) {
req.Header.Add("Accept", "application/json")
}
resp, err := r.httpClient.PostCustomized(url, payload, setHeaders)
if err != nil {
return bosherr.WrapErrorf(err, "Performing request POST '%s'", url)
}
respBody, err := r.readResponse(resp)
if err != nil {
return err
}
err = json.Unmarshal(respBody, &response)
if err != nil {
return bosherr.WrapError(err, "Unmarshaling UAA response")
}
return nil
}
func (r ClientRequest) readResponse(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, bosherr.WrapError(err, "Reading UAA response")
}
if resp.StatusCode != http.StatusOK {
msg := "UAA responded with non-successful status code '%d' response '%s'"
return nil, bosherr.Errorf(msg, resp.StatusCode, respBody)
}
return respBody, nil
}