-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
58 lines (44 loc) · 1.4 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
package restlib
import (
"bytes"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
"net/url"
"stash.sbab.se/TNT/ansible2structurizr/openstack/apiclient/urlutil"
)
type APIClient interface {
// MessageType retrieves the type of messages sent and received over the API
MessageType() MessageType
// Host retrieves the API host server
Host() *url.URL
// Call will send the message to the API host, and expect a response message in return
Call(path string, request *Message, response *Message) (err error)
}
// Call is a default implementation of the APIClient.Call method
func Call(c APIClient, path string, request *Message, response *Message) (err error) {
var data []byte
if data, err = c.MessageType().Serializer().Marshal(request); err != nil {
return err
}
var body = bytes.NewReader(data)
var httpReq *http.Request
if httpReq, err = http.NewRequest(request.Method, urlutil.WithPath(path, c.Host()).String(), body); err != nil {
return err
}
var httpResp *http.Response
if httpResp, err = http.DefaultClient.Do(httpReq); err != nil {
return err
}
if response != nil {
if data, err = ioutil.ReadAll(httpResp.Body); err != nil {
return err
}
if err = c.MessageType().Serializer().Unmarshal(data, response); err != nil {
return errors.Wrapf(err, "unable to de-serialize response data")
}
response.Status = httpResp.StatusCode
response.Header = httpResp.Header
}
return nil
}