-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
169 lines (139 loc) · 3.66 KB
/
rest.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package mode
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
const (
defaultHTTPTimeout = time.Second * 10
defaultHTTPKeepAliveTimeout = time.Minute * 5
defaultHTTPKeepAliveMaxConn = 5
defaultUserAgent = "GoDeviceSDK/" + sdkVersion
)
var (
httpTransport = &http.Transport{
MaxIdleConnsPerHost: defaultHTTPKeepAliveMaxConn,
IdleConnTimeout: defaultHTTPKeepAliveTimeout,
}
httpClient = &http.Client{
Transport: httpTransport,
Timeout: defaultHTTPTimeout,
}
)
// RESTError represents an error returned by the MODE REST API.
type RESTError struct {
statusCode int
reason string
data map[string]interface{}
}
func newRESTError(statusCode int, jsonBytes []byte) *RESTError {
restErr := &RESTError{statusCode: statusCode}
var fields struct {
Reason string `json:"reason"`
Data map[string]interface{} `json:"data"`
}
if err := json.Unmarshal(jsonBytes, &fields); err == nil {
restErr.reason = fields.Reason
restErr.data = fields.Data
} else {
restErr.reason = "UNKNOWN"
}
return restErr
}
// Error returns a summary of the error.
func (e *RESTError) Error() string {
return fmt.Sprintf("server returned status %d (reason: %s)", e.statusCode, e.reason)
}
// Reason returns the specific reason for the error.
func (e *RESTError) Reason() string {
return e.reason
}
// StatusCode returns the HTTP status code provided by the API server.
func (e *RESTError) StatusCode() int {
return e.statusCode
}
// Data returns any additional data associated with this error, or nil.
func (e *RESTError) Data() map[string]interface{} {
return e.data
}
func makeRESTCallURL(path string) string {
var proto string
if restTLS {
proto = "https"
} else {
proto = "http"
}
return fmt.Sprintf("%s://%s:%d%s", proto, restHost, restPort, path)
}
func makeRESTAuth(authToken string) string {
return fmt.Sprintf("ModeCloud %s", authToken)
}
func makeRESTCall(method string, path string, dc *DeviceContext, data interface{}, resData interface{}) error {
url := makeRESTCallURL(path)
authToken := ""
if dc != nil {
if dc.TLSClientAuth {
if dc.TLSConfig == nil {
logError("Client certificate is not set")
return errors.New("client certificate is not set")
}
httpTransport.TLSClientConfig = dc.TLSConfig
} else {
authToken = dc.AuthToken
}
}
var body io.Reader
if data != nil {
jsonBytes, err := json.Marshal(data)
if err != nil {
logError("Failed to encode data to JSON: %s", err.Error())
return err
}
body = bytes.NewReader(jsonBytes)
}
request, err := http.NewRequest(method, url, body)
if err != nil {
logError("Failed to set up HTTP request: %s", err.Error())
return err
}
request.Header.Add("User-Agent", defaultUserAgent)
if authToken != "" {
request.Header.Add("Authorization", makeRESTAuth(authToken))
}
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
res, err := httpClient.Do(request)
if err != nil {
logError("Failed to make HTTP request: %s", err.Error())
return err
}
defer res.Body.Close()
jsonBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
logError("Failed to read HTTP response body: %s", err.Error())
return err
}
logInfo("REST API response code %d", res.StatusCode)
if res.StatusCode == http.StatusNoContent {
return nil
}
if res.StatusCode == http.StatusOK || res.StatusCode == http.StatusCreated {
if resData == nil {
return nil
} else {
if err := json.Unmarshal(jsonBytes, resData); err == nil {
return nil
} else {
logError("Failed to parse JSON response: %s", err.Error())
return err
}
}
}
return newRESTError(res.StatusCode, jsonBytes)
}