forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent_request.go
67 lines (54 loc) · 1.53 KB
/
agent_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
package http
import (
"encoding/json"
"io/ioutil"
"net/http"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
"github.com/cloudfoundry/bosh-utils/httpclient"
)
type AgentRequestMessage struct {
Method string `json:"method"`
Arguments []interface{} `json:"arguments"`
ReplyTo string `json:"reply_to"`
}
type agentRequest struct {
directorID string
endpoint string
httpClient *httpclient.HTTPClient
}
func (r agentRequest) Send(method string, arguments []interface{}, response Response) error {
postBody := AgentRequestMessage{
Method: method,
Arguments: arguments,
ReplyTo: r.directorID,
}
agentRequestJSON, err := json.Marshal(postBody)
if err != nil {
return bosherr.WrapError(err, "Marshaling agent request")
}
httpResponse, err := r.httpClient.PostCustomized(r.endpoint, agentRequestJSON, func(r *http.Request) {
r.Header["Content-type"] = []string{"application/json"}
})
if err != nil {
return bosherr.WrapErrorf(err, "Performing request to agent")
}
defer func() {
_ = httpResponse.Body.Close()
}()
if httpResponse.StatusCode != http.StatusOK {
return bosherr.Errorf("Agent responded with non-successful status code: %d", httpResponse.StatusCode)
}
responseBody, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return bosherr.WrapError(err, "Reading agent response")
}
err = response.Unmarshal(responseBody)
if err != nil {
return bosherr.WrapError(err, "Unmarshaling agent response")
}
err = response.ServerError()
if err != nil {
return err
}
return nil
}