-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
112 lines (91 loc) · 2.41 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package manageiq
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
const ()
// LogLevel defines a type that can set the desired level of logging the SDK will generate.
type LogLevel uint
const (
// LogOff will disable all SDK logging. This is the default log level
LogOff LogLevel = iota * (1 << 8)
// LogDebug will enable detailed SDK debug logs. It will log requests (including arguments),
// response and body contents.
LogDebug
// LogInfo will log SDK request (not including arguments) and responses.
LogInfo
)
func (l LogLevel) shouldLog(v LogLevel) bool {
return l > v || l&v == v
}
// Client contains parameters for configuring the SDK.
type Client struct {
// Authenticator for the client
Authenticator Authenticator
// apiKey used to talk ManageIQ
apiKey string
// Logging level for SDK generated logs
LogLevel LogLevel
// No need to set -- for testing only
HTTPClient *http.Client
}
type ClientParams struct {
BaseURL string
LogLevel LogLevel
Insecure bool
}
func NewClient(authenticator Authenticator, param ClientParams) *Client {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: param.Insecure},
}
return &Client{
Authenticator: authenticator,
HTTPClient: &http.Client{
Timeout: time.Minute,
Transport: tr,
},
}
}
type errorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{}
}
func (c *Client) sendRequest(req *http.Request, v interface{}) (*DetailedResponse, error) {
if err := c.Authenticator.Authenticate(req); err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json; charset=utf-8")
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return nil, errors.New(errRes.Message)
}
return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
detailedResponse := &DetailedResponse{
StatusCode: res.StatusCode,
Headers: res.Header,
Result: v,
RawResult: body,
}
if err = json.NewDecoder(bytes.NewReader(body)).Decode(&detailedResponse.Result); err != nil {
return nil, err
}
return detailedResponse, nil
}