-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
74 lines (62 loc) · 1.94 KB
/
client.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
package jolokiago
import (
"bytes"
"encoding/json"
"github.com/codingchipmunk/jolokiago/messages"
"io"
"io/ioutil"
"net/http"
)
const contentType = "application/json"
// Client holds fields needed to communicate with a Jolokia agent
type Client struct {
url string
client *http.Client
sseID string
}
// MakePOSTRequest makes an POST request to the Jolokia agent using the http.Client given to the client struct
func (jc *Client) MakePOSTRequest(request messages.POSTRequest) (resp messages.ResponseRoot, err error) {
// Marshal the request
body, err := request.POSTBody()
if err != nil {
return
}
// Use the http client to make the request
httpResp, err := jc.client.Post(jc.url, contentType, bytes.NewReader(body))
if err != nil {
return
}
// Immediately defer Body.Close() (idiomatic)
defer httpResp.Body.Close()
return unmarshalResponse(httpResp.Body)
}
// MakeGETRequest makes an GET request to the Jolokia agent using the http.Client given to the client struct
func (jc *Client) MakeGETRequest(request messages.GETRequest) (resp messages.ResponseRoot, err error) {
// Create a new Buffer for the url and the get-params
urlBuff := bytes.Buffer{}
urlBuff.WriteString(jc.url)
bts, err := request.GetAppendix()
if err != nil {
return
}
urlBuff.Write(bts)
// Use the http client to make the request
httpResp, err := jc.client.Get(urlBuff.String())
if err != nil {
return
}
// Immediately defer Body.Close() (idiomatic)
defer httpResp.Body.Close()
return unmarshalResponse(httpResp.Body)
}
// unmarshalResponse unmarshals the response from a response body (or any struct implementing the io.ReadCloser interface)
func unmarshalResponse(responseBody io.ReadCloser) (resp messages.ResponseRoot, err error) {
// Read the response body
httpBody, err := ioutil.ReadAll(responseBody)
if err != nil {
return
}
// Unmarshal the response body into the response.ResponseRoot struct
err = json.Unmarshal(httpBody, &resp)
return
}